Next →

Closures and Lexical Scope in JavaScript

A closure is a function that remembers the environment in which it was created. This means it has access to variables from its outer (enclosing) scope, even after the outer function has finished executing.

Example of Closure

function outer() {
  let count = 0;
  
  function inner() {
    count++;
    return count;
  }
  
  return inner;
}

const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2

Here, inner forms a closure that retains access to count defined in outer.

Lexical Scope

JavaScript uses lexical scoping — the scope is determined by where functions and blocks are defined, not where they are called.