Deleting value when calling Javascript function

Asked

Viewed 42 times

4

The code below does not pass a value to y but still the code works, someone knows 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

1 answer

11


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

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

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

In that case you might 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.