0

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
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • 3
    `console.log(add(1)(2))` logs `3` and is the correct one. _“`add` is defined as an anonymous function with input `x` and output as another anonymous function `(y) => x + y`”_ — Almost correct: `add` is not anonymous itself (`add.name === "add"`; see [NamedEvaluation](//tc39.es/ecma262/#sec-let-and-const-declarations-runtime-semantics-evaluation)); everything else is correct. – Sebastian Simon Dec 27 '22 at 02:47
  • `console.log(add(1,2)())` also logs `NaN`. This is not reproducible. Try again. – Sebastian Simon Dec 27 '22 at 02:53
  • 1
    I tried `console.log(add(1)(2))` in my browser's console, and here's the [result](https://i.stack.imgur.com/urmPW.png). This one is correct because function `add` requires a parameter `x`, and it returns a anonymous function which requires a parameter `y`. Happy to help! – yxzlwz Dec 27 '22 at 02:53

0 Answers0