What is a closure in JavaScript?

Closure: It’s not a complex concept. Yet it’s hard to describe. Sure, a lot of programming jargon is abstract and requires a little bending of one’s mind. Polymorphism, reflection, encapsulation — hell, even abstraction is an abstract concept.

In my own effort to understand closures better, I’ve compiled the best descriptions of JavaScript closures from authoritative sources on the Web. Hopefully this will be useful to you, too.

Mozilla’s docs describe closures like so:

Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions ‘remember’ the environment in which they were created.

In JavaScript: The Good Parts, Douglas Crockford describes closures:

Functions can be defined inside of other functions. An inner function of course has access to its parameters and variables. An inner function also enjoys access to the parameters and variables of the functions it is nested within. The function object created by a function literal contains a link to that outer context. This is called closure.

… inner functions get access to the parameters and variables of the functions they are defined within (with the exception of this and arguments).

Wikipedia’s not-so-elegant-but-sensical definition:

In programming languages, closures are techniques for implementing lexically scoped name binding in languages with first-class functions. Operationally, a closure is a record storing a function together with an environment: a mapping associating each free variable of the function (variables that are used locally, but defined in an enclosing scope) with the value or reference to which the name was bound when the closure was created. A closure — unlike a plain function — allows the function to access those captured variables through the closure’s copies of their values or references, even when the function is invoked outside their scope.

Stack Overflow has a hugely popular thread on the subject, complete with helpful examples. Another succinct definition:

a closure is one way of supporting first-class functions; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result.

Of course, most of this is hard to understand without some hands-on. Check out the Stack examples and write some experimental code yourself to really get your head around it.