I was looking at Mozillas developer site on javascript closure and they had this example of code.
function makeAdder(x){
return function (y) {
console.log(y + " this is y")
console.log(x + " this is x")
return x + y;
}
}
var add10 = makeAdder(10);
console.log(add10(2)); // 12
Now i understand the X attribute being set but what i dont get is how the scope of the y is being affected. I know its a return function but my brain went to mush trying to visualise how you could set a y when there was no ref to it. could someone explain?
makeAdderreturns a function to which you can pass theyparameter. It is set at the time of invocation, as opposed toxwhich is set at the time of creation of the new function (at the time of the invocation ofmakeAdder).For the case of this example, the output is equivalent to having written:
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.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:
In the above code,
iwill have iterated through the entire set before any of the buttons are clicked. Therefore, all buttons will alert whateverbuttons.lengthis. Instead, you could do the following:The difference here is that
iis 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 wheniwillhave 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: