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;}
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;