0
function makeMultiplier(multiplier) {
  var myFunc = function (x) {
    return multiplier * x;
  };

  return myFunc;
}

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

So I got this example from an online course, the console prints: 30

I don't exactly understand how the value 30 was obtained, below is what I think is how it is executed, but please do correct me if false.

  1. I assume first that the value of multiplier becomes 3, then the function makeMultiplier returns 3 * X.

  2. From here, by assigning var multiplyBy3 = makeMultiplier(3), essentially multiplyBy3 is now a function that returns 3 * X.

  3. Therefore when 10 is plugged in, it returns 3 * 10 = 30.

Questions
  • 117
  • 3
  • 3
  • 9
  • Yes, `makeMultiplier(3)` does return a function. (That it is assigned to a variable isn't strictly necessary) – Bergi Mar 12 '18 at 18:51

3 Answers3

5

Yes, you are correct, remember that functions can be passed around to and from variables and other functions.

  • makeMultiplier returns a reference to a function closure, it doesn't execute it yet.
  • var multiplyBy3 = makeMultiplier(3); Puts the value 3 into the closure function, and returns a reference to it (still doesn't execute it yet).

At this stage we have:

function multiplyBy3(x) {
    return 3 * x;
}

console.log(multiplyBy3(10));
  • multiplyBy3(10) calls the reference to the closure function and passes in 10.
1

The example you posted is also referred to as "currying". Here's another javascript example of currying.

I do recommend that you get in the habit of using ES6 syntax. Your example rewritten in ES6:

const makeMultiplier = multiplier => x => multiplier * x;
const multiplyBy3 = makeMultiplier(3);
console.log( multiplyBy3(10) ); // 30

or

console.log( makeMultiplier(3)(10) ); //30
wLc
  • 968
  • 12
  • 15
0

Correct. This is what is known as a 'closure' (a function that returns another function that has access to the scope of the parent function.