JS: 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() {
    let x = 0;
    function f() {
        x += 1;
        return x;
    };
    return f;
};

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

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

In this example, the function myContext() 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.

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, the outter function c and assign it to a variable like this: const g = c();.
  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() {
    let x = 0;

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

const 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.

Function with State, Using Properties

JavaScript function is a object [see JS: Object Type], 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.

JS Function

  1. Define Function
  2. Arrow Function ⭐
  3. Function Params
  4. “arguments” Object
  5. Rest Params ⭐
  6. Arg Default Value ⭐
  7. Arg Destructure ⭐
  8. f Declaration vs Expression
  9. Closure
  10. f call apply bind
  11. Functional Programing
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog