Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the benefits of a closure, and when are they typically used?

I'm a web developer, but lots of folks are looking for slightly more advanced skills and understanding closures seems to be at the forefront of this.

I get the whole "execution context creating a reference to a variable that doesnt ever get destroyed" thing, but really, is this some sort of private or static variable implementation in JavaScript?

like image 294
qodeninja Avatar asked Nov 05 '10 00:11

qodeninja


People also ask

When should closures be used?

Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.

What is closure and when should you use it?

In JavaScript, a closure is a function that references variables in the outer scope from its inner scope. The closure preserves the outer scope inside its inner scope. To understand the closures, you need to know how the lexical scoping works first.

What is a closure in simple terms?

Definition of closure 1 : an act of closing : the condition of being closed closure of the eyelids business closures the closure of the factory. 2 : an often comforting or satisfying sense of finality victims needing closure also : something (such as a satisfying ending) that provides such a sense.


1 Answers

They can be good for lots of things, for example, visibility (like private members in traditional OO).

var count = function(num) {

   return function(add) {
       add = add || 1;
       num += add;
       return num;
   }

}

See it.

My count() can be seeded with a number. When I assign a variable to the return, I can call it with an optional number to add to the internal num (an argument originally, but still part of the scope of the returned function).

This is a pretty good overview.

See also on Stack Overflow

  • What is a practical use for a closure in JavaScript?
  • How does a javascript closure work ?
  • When actually is a closure created?
  • more...
like image 79
alex Avatar answered Sep 29 '22 14:09

alex