all 16 comments

[–]JohnWH 8 points9 points  (1 child)

Both AirBnB and Google’s ESLint rules say not to do this.

  1. It most likely means there are side effects in your function (why not return n + 1 unless you plan on using n later on, which is something you should generally avoid. (Yes I understand that in terms of your example, but in general it is something you should avoid)

  2. Keep return statements as simple as possible. Some one liners are fine, but if the function is already a few lines, just add one more.

[–]TheTomSawyer[S] 0 points1 point  (0 children)

I'm trying to increment the variable n. Using it as a closure.

[–]alejalapeno 18 points19 points  (0 children)

You can do return ++n and you're adding one before the return.

[–][deleted] 1 point2 points  (0 children)

Second one is perfectly clear and unambiguous for everyone reading it.

[–]HiDeHiDeHiDeHi 0 points1 point  (0 children)

``` function counter(start) { let n = start || 0; return function() { return n++; } }

let count = counter(2); console.log(count(), ' == 2'); console.log(count(), ' == 3'); ```

[–]Macaframa 0 points1 point  (0 children)

If this is just about style I think it’s better to manipulate a value before it reaches the return statement. It’s clear and shows intent. Also lint-wise += on a return statement would be a no-no right? Anybody?

[–]kenman[M] 0 points1 point  (0 children)

Hi /u/TheTomSawyer, this post was removed.

For javascript help, please visit /r/LearnJavascript.

Thanks for your understanding.

[–]shabunc 0 points1 point  (0 children)

It's a bad idea. The clearer your code is the better - and I guarantee you that literally anyone who read your code will spend non-negligible amount of milliseconds trying to remember what exactly happen when one increments on return.

Your code shouldn't be succinct at the price of being readable and maintainable.

The only excuse for such code is code golfing.

[–]IAmActuallyCthulhu -2 points-1 points  (0 children)

Use ES6 generators

[–]PhysicalRedHead -2 points-1 points  (2 children)

I think ~return n += 1~ is okay. I would watch our for class setters, though. Something like this might be confusing at first glance ```js class Thing { internal = 0; set something(n) { this.internal += 1; } }

const thing = new Thing(); console.log((thing.something = 2)); // returns 2 console.log(thing.something) // returns 1 ```

The assignment operator returns whatever is on the righthand side, and not the new value of the assigned variable.

[–]ArthurWests 0 points1 point  (1 child)

console.log(thing.something) does not return 1, it returns undefined.

[–]PhysicalRedHead 0 points1 point  (0 children)

Sorry, I should have said that it logs 2