Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Closures

A closure is a function together with access to the lexical environment where it was created. It lets the function use outer variables even after the function that created them has returned. It retains access to bindings, not a copy of their initial values.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

function makeCounter() {
  let count = 0;
  return function increment() {
    count += 1;
    return count;
  };
}

A closure is a function together with access to the lexical environment where it was created. Variable names are resolved according to code nesting, not the location of a later call. closure names a concept, not a JavaScript keyword; closures have no separate operator or special syntax.

The function retains access to outer bindings, which associate names with variables, rather than a frozen copy of their values. It can read the current value and update it if the binding is mutable. In the specification model, a function's internal [[Environment]] slot points to its outer environment; this is not a property accessible from JavaScript code.

In the example, increment still uses count after the call to makeCounter has returned. Successive calls to first update the same binding. However, each call to makeCounter creates a separate count, so second has independent state. The output is 1, 2, 1, 3, in that order.

Closures are useful for retaining state and creating callbacks. Several functions created in the same environment can share one binding—do not assume each has its own copy. The mechanism itself does not require Web APIs; the example uses ECMAScript 2015 let and const syntax and a console supplied by the host environment.

Examples

function makeCounter() {
  let count = 0;
  return function increment() {
    count += 1;
    return count;
  };
}

const first = makeCounter();
const second = makeCounter();

console.log(first());
console.log(first());
console.log(second());
console.log(first());

Result

1
2
1
3

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources