0

I can't understand this code ,especially how value of x in "myfunc" takes up the value when called.... what does thois line of code means "var multiplyBy3 = makeMultiplier(3);" Please note console returns result 30.

// Function factory
function makeMultiplier(multiplier) {
  var myFunc = function (x) {
    return multiplier * x;
  };

  return myFunc;
}

var multiplyBy3 = makeMultiplier(3);
console.log(multiplyBy3(10));

2 Answers2

0

This code is a good demonstration of JavaScript's closures.

When you run:

var multiplyBy3 = makeMultiplier(3);

makeMultiplier is called, which creates a local variable myFunc, whose value is a JavaScript function. myFunc's body references multiplier, which comes from the parameter to makeMultiplier(multiplier), and x, which comes from the function's own parameter x.

makeMultiplier then returns myFunc, which is now a closure since the variable in scope when it was created, namely multiplier, is still intact, even though makeMultiplier itself has exited.

Now, since the return value of makeMultiplier(3) was a function, multiplyBy3 now has that function as its value. As such, you can now call multiplyBy3 as a regular function, which is what happens in the next line.

console.log(multiplyBy3(10));

This line logs the return value of multiplyBy3, which was multiplier * x.

x was just passed in to the function as its only parameter, so x is 10.
multiplier is the same as the multiplier from the previous call to makeMultiplier, so multiplier is 3.

Thus, multiplyBy3 returns 3 * 10, which is 30, which is the output that you see logged in your browser's console.

ArkaneMoose
  • 111
  • 2
  • 7
0

I added a little documentation to the code to help clarify what is going on.

// --------------------
// A function that when executed returns a new function
// --------------------
function makeMultiplier(multiplier) {

  console.log("multiplier for this new function shall be: " + multiplier);

  // --------------------
  // A function that takes a parameter "x" and
  // returns "x" multiplied by "multiplier"
  // --------------------
  var myFunc = function(x) {
    console.log("multiplying " + multiplier + " * " + x);
    return (multiplier  * x);
  };
  // --------------------

  return myFunc;
}
// --------------------

// --------------------
// use makeMultiplier to create a new function
// --------------------
var multiplyBy3 = makeMultiplier(3);
// --------------------

// --------------------
// use our new function
// --------------------
var result = multiplyBy3(10);
// --------------------

console.log("results in " + result);
JonSG
  • 10,542
  • 2
  • 25
  • 36