Course contentsShow
← Computer Science
Lesson 2137 of 2,87248. Programming ParadigmsFree lesson

Closures and Lexical Scope

Capture variables from enclosing scopes to create stateful behavior without mutation.

Closures and Lexical Scope

What You'll Learn

You'll discover how functions can "remember" variables from their creation environment, enabling stateful behavior without modifying existing data.

The Core Idea

Lexical scope means a function can access variables from the environment where it was defined, not where it's called. When a function remembers and carries these outer variables with it, we call that combination a closure.

Think of a closure like a backpack: when a function is created, it packs up references to variables from its surrounding scope and carries them wherever it goes, even after the outer function has finished executing.

Why This Matters

Closures let you create functions with "private" state without using mutable variables or objects. Each closure maintains its own independent copy of the captured variables:

function makeCounter() {
  let count = 0;  // captured variable
  
  return function() {
    count = count + 1;  // accesses outer scope
    return count;
  };
}

const counter1 = makeCounter();
const counter2 = makeCounter();

counter1();  // 1
counter1();  // 2
counter2();  // 1 (independent state!)

Here, each returned function "closes over" its own count variable. The inner function remembers the environment where it was born, even though makeCounter has finished running.

Functional Programming Connection

Closures enable powerful functional patterns: you can return customized functions, build function factories, and maintain state purely through scope rather than mutation of shared data structures. Combined with higher-order functions, closures become a fundamental tool for creating flexible, composable code.

Key Takeaway: Closures capture variables from their defining scope, allowing functions to carry persistent, encapsulated state without explicit mutation or objects—a cornerstone of functional programming's approach to statefulness.