After reading about closures in JavaScript, I am still unable to understand where are they used? If there were no closures then how would the things be done alternately (if possible) and what does the use of closures simplify. If someone can explain this with some code examples in JavaScript it would be helpful. Any links to articles explaining this are also welcome.
I have read this article mentioned in a similar question. It explains with code like this
function makeSizer(size) {
return function() {
document.body.style.fontSize = size + 'px';
};
}
var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);
document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;
But why would I do like this when instead I can easily create a function like this
function sizer(size) {
document.body.style.fontSize = size + 'px';
};
document.getElementById('size-12').onclick = function(){sizer(12)};
document.getElementById('size-14').onclick = function(){sizer(14)};
document.getElementById('size-16').onclick = function(){sizer(16)};
I think this SO answer pretty much explain the concept in detail.
After reading this my understanding is that closures are there to make functions as first class objects. Functions as first class objects are really helpful as they can be passed like arguments and make certain things quite easy.
Also one more benefit of using closures is probably they can be used to make members private in JavaScript as explained in this post.