I am working my way through Eloquent Javascript and I came across a code snippet that looks like this:
function greaterThan(x) {
return function(y) {
return y > x;
};
}
var greaterThanTen = greaterThan(10);
show(greaterThanTen(9));
Is there any real use-case to defining the function like this with an anonymous function inside of it? Wouldn’t it be much simpler to do this:
function greaterThan(x,y){
return x > y;
}
var greaterThanTen = greaterThan(9, 10);
any ideas/comments/suggestions would be very helpful.
This is an example of a “closure”. Basically, a call to
greaterThan()gives you a function. That function, instead of just a mere function, carries with it the value ofx– it’s like embedding the value ofxpermanently into the function.Closures are one of the great features of JavaScript. One of it’s great uses is to emulate private variables.