JavaScript: Closure

By Xah Lee. Date: . Last updated: .

JavaScript supports Closure . Practically, a function with local state.

Here is 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, call 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 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.

JavaScript Function

JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types





Object and Inheritance



Iterable 🌟