Suppressing value when calling Javascript function

4

The code below does not pass a value to y but the code works anyway, does anyone know how it works?

I would like to learn more about, does anyone know the name of this javascript feature?

function base(x) {
  return function produto(y) {
    return x * y;
  }
}

var f = base(2);
var g = base(-1);

console.log(f(2) + g(-1)); // 5
    
asked by anonymous 09.06.2017 / 20:47

1 answer

11

This concept is called high-order-function . That is a function that returns another, configured for a given process.

Programming in this way integrates into the functional programming philosophy, because in this case the function base is pure and always returns a function, therefore it is an instrument of application flow. >

In this case, when you invoke the base function, you receive a high-order function that receives an argument and multiplies what has already been preconfigured.

In this case you could even have clearer names like:

function base(x){
    return function produto(y){
           return x * y;
    }
}

var vezesDois = base(2);
var inverterSinal = base(-1);

console.log(vezesDois(7)); // 14
console.log(inverterSinal(435)); // -435
    
09.06.2017 / 20:50