JS: Closure

By Xah Lee. Date: . Last updated: .

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

Here is a example of closure in JavaScript.

function ff() {
  let x = 0;
  function gg() {
    x += 1;
    return x;
  }
  return gg;
}

const hh = ff();
// hh is now a closure

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

In this example, the function ff() returns the function gg.

ff() sets up a variable x, and the inner function gg uses it. When ff() is called, gg is returned. The function gg still has its scope context.

Closure by Arrow Function

const ff = (() => {
  let x = 0;
  return (() => {
    x += 1;
    return x;
  });
});

const hh = ff();
// hh is now a closure

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

Closure with Shared Variable Context

More than one function can share the same variable context.

// example of closure functions sharing context

function ff() {
  let x = 0;

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

const c = ff();

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 ff 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 ff() {
  ff.x += 1;
  return ff.x;
}

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

console.log(ff() === 1);
console.log(ff() === 2);
console.log(ff() === 3);

This is simpler than closure but achieve the same effect.

JavaScript, Function

BUY Ξ£JS JavaScript in Depth