Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java-script arrow function returns (x++,x) [duplicate]

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;}
like image 704
Babak Karimi Asl Avatar asked Apr 25 '20 19:04

Babak Karimi Asl


People also ask

What does () => mean in JavaScript?

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.

Can I return an arrow function JavaScript?

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.

What do arrow functions return?

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 does => mean in programming?

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) {...} .


1 Answers

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;
like image 89
Jonas Wilms Avatar answered Oct 01 '22 11:10

Jonas Wilms