1 min read

Closures Continued: Lexical vs. Dynamic Scope

It is helpful to contrast lexical scope with dynamic scope to understand why closures work the way they do.

Lexical Scope (JavaScript)

Scope is determined by where the function is defined in the source code. The inner function "remembers" the environment where it was created.

Dynamic Scope

Scope is determined by where the function is called (the call stack).

Example Comparison

const value = "Global";

function printValue() {
  console.log(value);
}

function wrapper() {
  const value = "Local";
  printValue();
}

wrapper();
  • In JavaScript (Lexical): printValue was defined in the global scope, so it sees value = "Global". The output is "Global".
  • If JavaScript were Dynamic: printValue is called inside wrapper, so it would see wrapper's value. The output would be "Local".

Closures rely on lexical scoping to persist data. If scope were dynamic, the data a function accesses would change depending on who called it, breaking the encapsulation that closures provide.

programming/javascript/vanilla/closures programming/javascript/vanilla/javascript