简体   繁体   中英

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);

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)

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM