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;}
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30

3 Answers3

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;
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
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;}
Ufuk
  • 448
  • 5
  • 9
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
Maciek Leks
  • 1,288
  • 11
  • 21