9

i don't know how the code:const countFrom = x => () => (x++, x); from here, works:

const countFrom = x => () => (x++, x);
let a = countFrom(1)

console.log('output:', a()) // output: 2
console.log('output:', a()) // output: 3
console.log('output:', a()) // output: 4
console.log('output:', a()) // output: 5
.as-console-wrapper {min-height: 100%!important; top: 0;}

4
  • 1
    This is just comma operator. It evaluates each of its operands from left to right and returns the value of the last operand. Commented Apr 25, 2020 at 19:25
  • 2
    countFrom receives x as an argument and then returns a closure that when called increments x and returns its value. (x++, x) is just shorthand for { x++; return x; } Commented Apr 25, 2020 at 19:27
  • Study concept of closures. Commented Apr 25, 2020 at 19:28
  • @Aleksey best answer Commented Apr 25, 2020 at 20:16

3 Answers 3

4

x is a variable inside the outer (x =>) function, therefore all inner functions (() => (x++, x)) share the same variable. x++ post increments that variable whenever the inner function executes. The comma operator (..., x) evaluates to the last comma seperated expression, x in this case.

It is maybe easier to understand without the comma operator:

 const counter = x => () => x = x + 1;
Sign up to request clarification or add additional context in comments.

3 Comments

I wonder why nobody has mentioned const counter = x => () => ++x; yet…
@bergi yeah, thought that x = x + 1 was easier to understand, would've chosen ++x if I'd write it for myself though
@Bergi yes that is better
1

//const countFrom = x => () => (x++, x);
//Lets refactor the code a bit:

function countFrom(x){
return function(){
x++;
return x;
}
}

let a = countFrom(1)
//now a is the returned function at line 5, and x is stored as a local variable.
console.log('output:', a()) // output: 2 you call the function at line 5 so it adds 1 to x and returns it
.as-console-wrapper {min-height: 100%!important; top: 0;}

Comments

0

It's quite simple if you understand some aspects:

  1. You have got two functions in the first line, not only one: the first one returns the second function ()=> (x++,x) (see what closure is)
  2. Inside round bracket you see comma operator and the result of the statement is the last operand of the comma operator (here x),
  3. The round bracket works like return x, that is => (x) is the same as => return x

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.