Why do we have closures in JavaScript?

Viewed 5891

Am wrapping my head around JavaScript closures and am at a point where things are falling in place; i.e a closure is the local variables for a function - kept alive after the function has returned, or a closure is a stack-frame which is not deallocated when the function returns.

Am starting to understand this concept, but the more i understand the more i keep on wondering why do we have to use them.

An example like this one makes me understand the concept but leaves me asking, there is a simpler way of doing this!

function sayHello(name) {
   var text = 'Hello ' + name;
   var sayAlert = function() { alert(text); }
   sayAlert();
}
sayHello('Gath');

Am just wondering why do i have to keep local variable alive? after the function has exited?

Where can i get examples showing of solutions implemented by closure and that nothing else would have worked but closures?

5 Answers
Related