Saturday 30 April 2016

Javascript function in Eloquent Javascript



How does greaterThanTen(9) become the y variable in the return function? What I mean is how does the parameter (9) become the y in the return function argument? Wouldn't 9 be replaced with x since greaterThanTen = greaterThan(10)? Wouldn't the 9 just replace the x = 10 parameter? I just don't understand how that 9 parameter is getting to y in the return function.



 function greaterThan(x) {
return function(y) {
return y > x;
};
}

var greaterThanTen = greaterThan(10);
show(greaterThanTen(9));

Answer



It doesn't "become the y variable". The function greaterThan returns a function, and the value passed to greaterThan is "captured" in that returned function.



In other words, greaterThan(10) creates the following function:



function(y) { return y > 10; }


It's similar to writing:



function greaterThan10(y) { return y > 10; }


Functions that create functions take advantage of closures ("the thing that 'captures' the 10).



The advantage is that you don't need to keep writing greaterThanNnn functions for every number you want to use, you just call greaterThan(n) for whatever you need. This is a contrived, but popular, example, of course.



For chunks of info relating to referencing functions, when to use () and when not to, and some more realistic examples, see also:




No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...