[SOLVED] What is the value of an undefined parameter?

Issue

This Content is from Stack Overflow. Question asked by NeophyteLou

I’m having trouble understanding the behavior of the code below:

function multiplier(factor){
    return number => number * factor;
}

let twice = multiplier(2);
console.log(twice(5));

At the function call multiplier(2), the value of 2 is returned to the binding twice, which is 2, but how so? This implies that the return statement would evaluate to 1 * 2, but the parameter number was never assigned a value. I was expecting undefined * 2, instead which would return undefined. Why is the parameter number assigned a value of 1?



Solution

What let twice = multiplier(2); does is stored following function in twice variable

function(number) {
 // factor variable value was set here
 return number * 2;
}

When you called

console.log(twice(5));

It runs function stored in twice variable as following

function(5) {
  return 5 * 2;
}

Hence you got 10 on console.


This Question was asked in StackOverflow by NeophyteLou and Answered by Mursleen Amjad It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?