0Pricing
JavaScript Academy · Lesson

How Closures Capture State

Understand the lexical environment of closures.

What Is a Closure

A closure is a function bundled together with references to the variables from the scope where it was defined. The inner function "remembers" those variables even after the outer function has returned.

function outer() {
  const message = "hello";
  function inner() {
    console.log(message); // sees outer variable
  }
  inner();
}
outer(); // "hello"

Returning the Inner Function

The magic appears when you return the inner function. It keeps access to the outer variable even though outer has already finished running.

function outer() {
  const message = "remembered";
  return function () {
    console.log(message);
  };
}
const fn = outer();
fn(); // "remembered"

All lessons in this course

  1. How Closures Capture State
  2. Private Variables with Closures
  3. The Module Pattern (IIFE)
  4. Factory Functions
← Back to JavaScript Academy