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;}
It's a new feature that introduced in ES6 and is called arrow function. The left part denotes the input of a function and the right part the output of that function.
Arrow functions with curly brackets are the only way to get multiple statements or expressions inside the function body. The return statement stops the execution of a function and will return a value from the function. ⭐ ️A link to an awesome article on JavaScript's return statement rules here.
Arrow functions allow you to have an implicit return: values are returned without having to use the return keyword. This should be the correct answer, albeit needing a bit more explanation. Basically when the function body is an expression, not a block, that expression's value is returned implicitly.
What It Is. This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...} .
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With