Reputation: 313
I am able to assign the value of an anonymous function to a variable like this:
let x = function(y,z) { return y + z }(1,2);
The resulting value of x is 3. Following the guide at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions the equivalent using arrow functions should be this I think.
let x = (y = 1, z = 2) => { return y + z };
However the value of x in this case becomes NaN. Why is that?
Upvotes: 1
Views: 387
Reputation: 5234
let x = (y = 1, z = 2) => { return y + z }
assigns the function to the variable, not its call. To assign the function call to a variable first you need to call it. So, arrow function equivalent of let y = function(y,z) { return y + z }(1,2);
would be:
let x = ((y = 1, z = 2) => { return y + z })()
// or
let x2 = ((y, z) => { return y + z })(1,2)
// or
let x3 = ((y = 1, z = 2) => (y + z))()
// or
let x4 = ((y, z) => (y + z))(1,2)
let y = function(y,z) { return y + z }(1,2);
console.log(x)
console.log(x2)
console.log(x3)
console.log(x4)
console.log(y)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1