makeAdder returns a function to which you can pass the y parameter. It is set at the time of invocation, as opposed to x which is set at the time of creation of the new function (at the time of the invocation of makeAdder).
For the case of this example, the output is equivalent to having written:
function add10(y) {
return 10 + y;
}
console.log(add10(2)); // 12
Nothing new is going on here. The sample code is mainly trying to illustrate that a closure is being created for x.
So makeAdder, here, is aptly named: when you pass 10 to it, it gives you a function that will add 10 to everything you pass to that new function.
var add10 = makeAdder(10);
var add20 = makeAdder(20);
console.log(add10(1) + add20(1)); // 32
Surely, for the purpose of adding, it might be easier to just have a function that accepts two parameters and adds them. But this is not a lesson in adding, it is a lesson in closures.
A real world scenario might be something like this:
var buttons = document.getElementsByClassName('myButton');
for(var i = 0; i < buttons.length; i++) {
buttons[i].onclick = function() {
alert('You clicked button ' + i);
};
}
In the above code, i will have iterated through the entire set before any of the buttons are clicked. Therefore, all buttons will alert whatever buttons.length is. Instead, you could do the following:
var makeAlert = function(x) {
return function() {
alert('You clicked button ' + x);
};
};
for(var i = 0; i < buttons.length; i++) {
buttons[i].onclick = makeAlert(i);
}
The difference here is that i is not being used when the button is clicked (which will be after the entire iteration), but it is used during the iteration, at a time when i will
have a different value for each button.
Instead of creating a variable, makeAlert, you will often see this type of code being written as an anonymous function, invoked immediately. The code below is essentially equivalent to the code above:
for(var i = 0; i < buttons.length; i++) {
buttons[i].onclick = (function(x) {
return function() {
alert('You clicked button ' + x);
};
})(i);
}