I'm just come to javascript. I come across a code like this.
function makeAdder(a) {
return function(b) {
return a + b;
};
}
x = makeAdder(5);
Here the value of x(6) is 11. It seems x here is in a "uncomplete" state, waiting another argument to be finished? I don't know how this works. Can somebody explain to me? any reference would be appreciated.
This is a common technique in certain functional programming languages.
It's straightforward to do in Javascript, since functions are first-class values, and we can supply them as parameters to other functions, store them as properties of an object or as variables, or, as in this case, return them from other functions.
This is called a higher order function, since it either accepts a function parameter or returns a function result.
Values in Javascript have either global or function scope. The parameter a
is available in the scope of the outer function, and since the inner function was created in that scope, it has access to the variable a
. This is called a closure.
A number of libraries offer a curry
function that wraps up a plain function such as
function f(a, b) {
return a + b;
}
by using instead:
var g = curry(function f(a, b) {
return a + b;
});
so that now you can call it either as
g(6, 36); //=> 42
or as
var add6 = g(6);
add6(10); //=> 16;
But if you always want to do this in two steps, you can define it the way your makeAdder
does.
If you're interested in this style of programming, there are a number of libraries that try to help with it. My personal favorite is Ramda (disclaimer: I'm a core contributor to Ramda.)