0

I am a bit confused about this code, mainly the return function. I understand it takes the two parameters given and then multiplies them, but I don't know why or how the function number represents 5 in this case, and how it knows to multiply.

Everyone has been so helpful, I now understand what higher-order and realized it is just the arrow function that is making me confused. I need to try and understand them a little bit more.

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

let twice = multiplier(2);
console.log(twice(5));
  • 2
    `multiplier` is a higher-order function - it's a function that *returns a function*. For whatever reason the outer function is a regular function (`function (arg) { return thing }`) and the inner function is an arrow function (`arg => thing`). – jonrsharpe Jun 06 '20 at 16:42

2 Answers2

3

A function that returns a function is called a Higher-Order Function

the high-order function multiplier() accepts a single parameter factor, and returns a new (arrow) function.

the new function accepts a single parameter number, and returns the multiplication of factor with the number.

the returned function can access the factor argument due to the closure.

Mr.
  • 9,429
  • 13
  • 58
  • 82
1

Why do you use return number?

Well it's not the variable number which is returned, but a function instead, if you are not familiar with ES6 arrow functions syntax then here is the same using the old syntax, it is clear now what's going on right?

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

let twice = multiplier(2);
console.log(twice(5));
Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18