JavaScript: Closure

By Xah Lee. Date: . Last updated: .

Closure is a feature of computer languages. It is a way for function to maintain state, in a clean way. Practically speaking, the effect is the same as setting global variable inside function, but the variables are hidden and private.

Here's a example of closure in JavaScript.

// closure example

function myContext() {
    var x = 0;
    function f() {
        x += 1;
        return x;
    };
    return f;
};

// g is now function with closure
var g = myContext();

// g maintains a state
console.log(g());         // 1
console.log(g());         // 2
console.log(g());         // 3

In this example, the myContext() function returns the function f.

myContext() sets up a variable x, and the inner function f uses it. When myContext() is called, f is returned. The function f still has its scope context. (JavaScript function retains its original lexical scope chain.) 〔►see JavaScript Variable Scope: Function Level vs Block Level

How to create a closure:

  1. Define a function c.
  2. Declare some variables in c.
  3. Define a inner function f that use these variables.
  4. Return f in c.
  5. Now, call the outter function c and assign it to a variable like this: var g = c(); (similar to OOP's “new Something()”).
  6. This variable g is a function with closure.

Closure with Shared Variable Context

More than one function can share the same variable context.

// example of closure functions sharing context

function myContext() {
    var x = 0;

    return {
        "f": function () { x++; return x; },
        "g": function () { x--; return x; },
    };
};

var c = myContext();

console.log(c.f());         // 1
console.log(c.f());         // 2
console.log(c.f());         // 3

console.log(c.g());         // 2
console.log(c.g());         // 1
console.log(c.g());         // 0

Here, the function myContext returns a object, and the object has 2 properties, each's value is a function.

You can also return a array instead, so each function is by itself. Example:

// closure functions sharing context

function myContext() {
    var x = 0;

    return [
        function () { x++; return x; },
        function () { x--; return x; }
    ];
};

var c = myContext();
var f = c[0];
var g = c[1];

console.log(f());         // 1
console.log(f());         // 2
console.log(f());         // 3

console.log(g());         // 2
console.log(g());         // 1
console.log(g());         // 0

Function with State, Using Properties

JavaScript function is a object 〔►see JavaScript: What's Object?〕, so it has properties, and we can use the properties to maintain state.

// function with state, using properties

function f () {
    f.x += 1;
    return f.x;
};

f.x = 0;  // x is a property, used as state

console.log(f()); // 1
console.log(f()); // 2
console.log(f()); // 3

This is simpler than closure but achieve the same effect.

The disadvantage is that the variables (the properties) are not private. Anyone can see them.

Function Topic

  1. JavaScript: Define Function
  2. JavaScript: Function Parameters
  3. JavaScript: Variable/Function Declaration Order, Name Hoisting
  4. JavaScript Variable Scope: Function Level vs Block Level
  5. JavaScript: Function Declaration vs Function Expression
  6. JavaScript: Closure
  7. JavaScript: Functional Programing
  8. JavaScript: Function Call, Apply, Bind
  9. JavaScript: Function Argument Default Value
  10. JavaScript: Function Rest Parameters
  11. JavaScript: Arrow Function

  1. JavaScript: Function Object
  2. JavaScript: Function.prototype
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.