nocode
nocode

Reputation: 11

How does this higher order function work in JavaScript?

This code is confusing me.

Where does the inner function get the value for x.

function createMultiplier(multiplier) {
  return function(x) {
    return x * multiplier
  }
}

let doubleMe = createMultiplier(2);

Upvotes: 0

Views: 60

Answers (3)

Nathan Mc Grath
Nathan Mc Grath

Reputation: 308

It might be helpful to try and visual what happens when you call createMultiplier(2).

This will create a function that would look like this:

function doubleMe(x) {
  return x * 2; // 2 is the multiplier that we supplied to 'createMultiplier'
}

let answer = doubleMe(4);
// answer = 8;

another example:

let tripleMe = createMultiplier(3);

// is the same as writing this
function tripleMe(x) {
  return x * 3;
}

let answer = tripleMe(3);
// answer = 9;

Upvotes: 0

Dean Coakley
Dean Coakley

Reputation: 1877

The inner function will get the value x. When you invoke: doubleMe(16), for example.

When you call createMultiplier(2) you are setting the multiplier value.

Upvotes: 1

Pietro Nadalini
Pietro Nadalini

Reputation: 1800

This is called currying, what happens is that in the function createMultiplier you get a function and then when you execute that function you pass the parameter x

If you want to execute the function inside the function immediately, you can use this code createMultiplier(2)(5)

If you use console logs you can understand better what happens, I made an example bellow, so you can see first you only get a function and then you can pass the parameter x

function createMultiplier(multiplier) {
  return function(x) {
    return x * multiplier
  }
}

const doubleMe = createMultiplier(2);
console.log(doubleMe)
const result = doubleMe(5)
console.log(result)

Upvotes: 2

Related Questions