Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enclosing functions behaviour confusion

Tags:

javascript

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

var twice = multiplier(2);
console.log(twice(5));
//output 10

Can someone please explain why the 'number' parameter is not returned as undefined? I really struggle to understand how defining the variable 'twice' as a function with a fixed value 2 as its parameter can then be used as a function with passable parameter 5?

like image 273
user1088793 Avatar asked Dec 01 '25 05:12

user1088793


1 Answers

Short answer:

When you have var twice = multiplier(2); is the same as: twice = function (number) {return number * 2};

Imagine that Multiplier is a Class, which has a property factor (required to initialize the object), and when Multiplier is initialized it returns a function that takes in number and multiplies by factor.

like image 178
HNeiva Avatar answered Dec 03 '25 18:12

HNeiva