Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we have closures in JavaScript?

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?

like image 903
gath Avatar asked Jul 20 '10 10:07

gath


People also ask

Why do we need closures in JavaScript?

In JavaScript, closures are the primary mechanism used to enable data privacy. When you use closures for data privacy, the enclosed variables are only in scope within the containing (outer) function. You can't get at the data from an outside scope except through the object's privileged methods.

Why do we use closure?

Closures help in maintaining the state between function calls without using a global variable.

What is the practical use of closure in JavaScript?

Natively, JavaScript does not support the creation of private variables and methods. A common and practical use of closure is to emulate private variables and methods and allow data privacy. Methods defined within the closure scope are privileged.


1 Answers

Closures add expressive power to the language. There are some patterns that can be implemented very easily because of closures. A few examples that come to mind include:

  • The Module Pattern - Example by Eric Miraglia
  • Memoization - Example by Oliver Steele
  • Currying - Example by Dustin Diaz
like image 73
Daniel Vassallo Avatar answered Oct 04 '22 23:10

Daniel Vassallo