Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Scope and lifetime

Scope determines where a name refers to a particular binding. Lifetime concerns how long a binding or object remains needed during execution. A closure can preserve access to a local variable after its enclosing function returns.

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 () => ++count; }

Scope determines where in the code an identifier refers to a particular binding: an association between a name and a value. JavaScript uses lexical scope: lookup depends on code nesting, not on where a function is called. An inner declaration can shadow an outer name.

let and const are block-scoped; var inside a function is scoped to that function, not to an ordinary block. A let or const binding exists within its scope before its declaration executes, but remains uninitialized: access during this period, called the temporal dead zone (TDZ), throws ReferenceError. Scope and readability are therefore separate concerns.

Lifetime does not automatically end when execution leaves a block or returns from a function. A closure preserves access to surrounding bindings, not merely copies of their initial values. In the example, next still reads and updates count after makeCounter() returns. External code nevertheless cannot directly reference that local count.

Also distinguish a binding from an object: an object can remain reachable through another reference even when its original name is unavailable. Becoming unreachable can permit memory reclamation, but does not guarantee when or whether collection occurs. Leaving a scope is not an instruction to free memory. The example uses ECMAScript 2015 syntax; apart from displaying results through console.log, it requires no Web APIs.

Examples

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

const next = makeCounter();
console.log(next());
console.log(next());

try {
  console.log(count);
} catch (error) {
  console.log(error.name);
}

Result

1
2
ReferenceError

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