Closure is widely used in Javascript, I should say closure is used almost everywhere in Javascript. The closure is the corner stone of several widely used design pattern in Javascript. For a Javascript developer you will use closure in you day to day programming job.

Closure existed in other programming languages for a long time way before the Javascript, mostly functional programming language. But Javascript is the first language use closure heavily and brings closure to mainstream, most people start to pay attention to closure because of Javascript's ubiquitous in client side web programming.

What is closure in Javascript

The first question should be what is a closure since closure not only exist in Javascript, many programming languages support closure, most of them are functional language.

We should talk about closure in general first and then see what it looks like in a particular language like Javascript. Even closure is the official and most widely used name, there are actually many other synonymous which has a different name but in the nature they are just closure. Lets see some of them:

Anonymous function: A closure is simply an anonymous function. When you need to pass a function to another function or return a function from another function or store it in variable, you don't care about the name of the function because the origin name is useless, whats matter is the receiver of the function, for the receiver the origin name is meaningless. You will just define the function on the fly in most cases. Most closures show up in the form of anonymous function. When speak about anonymous function, people usually means closure.

Its not surprise people are using anonymous function and closure interchangeably.

A simplest anonymous function in Javascript:

function () {}
// what we can do about it?
// store it
var foo = function () {};
// call it immediately
(function () {})();
// pass parameter
function foo (callback) {
  // deal with callback
foo(function () {})
// return it
function foo () {
  return function () {};

Code block: A closure is a code block, a function consits of its name and its body, when we don't care and need the function name, the only thing left is the function body which essentially just a code block.

Inner function: A typical closure is an inner function. It can remember its parent function's local environment even after the parent function already exit.

Lambda function: The lambda function is just the academic name of anonymous function.

First class function: A closure must be a first class function and the language must support this feature to support closure. It means a function can be passed around as parameter or return value or stored in variable. This means a function can "escape" from the place its defined. A closure is such a function who escaped from its definition place but also retains visibility to its parent function's environment.

Use closure to implement module pattern

This is one of most useful thing you can do with closure. Using closure to encapsulate internal state and logic of a code unit, hiding internal information of the unit and provide clean interface to outside world. Much like an object which contains private data and code and provide public interface to outside.

The pattern goes like this, first write something like this


The left parenthesis define a function , which is a closure, and then execute it immediately with the right parenthesis. An anonymous function is a good fit here:

(function () {})();

The local scope will act as storage of the private state of the module and all the inner functions will share this storage, they act as member method of the module.

Suppose we want a logger, which can suppress output by logger level.

var logger = (function (){
  var level ;
  return {
    init : function (level_) {
      level = level_;
    info : function (msg) {
      if ( level >= 1 )
        console.log("INFO: " + msg);
    debug : function (msg) {
      if ( level >= 2 )
        console.log("DEBUG: " + msg);
    // ... more logging methods
logger.init(1);"info message");
logger.debug("debug message");

We set logger level to info, only info logger message gets output.