I was following the MDN documentation about functions as first-class objects and wasn’t able to understand this line of code.
How to execute the function add
? When I try this, I get these outputs.
// Function returning function.
const add = (x) => (y) => x + y;
console.log(add(1, 2)()) // undefined
console.log(add(1, 2)) // ƒ ()
console.log(add(1)(2)) // undefined
What is actually assigned to add
? According to my understanding, add
is defined as an anonymous function with input x
and output as another anonymous function (y) => x + y
. Then it should be equivalent to the following:
However, when I try a function
, I get these outputs:
const add1 = function(x) {
return (y) => x + y
};
console.log(add1(1, 2)()); // NaN
console.log(add1(1, 2)); // ƒ ()
console.log(add1(1)(2)); // 3