Course contentsShow
← JavaScript
Lesson 505 of 2,72313. ClosuresFree lesson

Nested Closures

A function can close over variables from multiple outer scopes, forming a chain through all enclosing lexical environments.

Nested Closures

What you'll learn: How functions can close over variables from multiple outer scopes, creating a chain of closures.

The Closure Chain

When you nest functions multiple levels deep, each inner function has access to its own scope plus all the scopes wrapping around it. This creates a chain where a deeply nested function can "see through" each layer of enclosing functions, all the way to the outermost scope it's defined in.

Think of it like nesting dolls: the innermost doll can see outward through every layer surrounding it.

How It Works

function outer() {
  const outerVar = 'outer';
  
  function middle() {
    const middleVar = 'middle';
    
    function inner() {
      const innerVar = 'inner';
      console.log(innerVar);   // own scope
      console.log(middleVar);  // middle's scope
      console.log(outerVar);   // outer's scope
    }
    
    return inner;
  }
  
  return middle;
}

const middleFn = outer();
const innerFn = middleFn();
innerFn();
// Logs: "inner", "middle", "outer"

The inner function closes over variables from both middle and outer. When inner executes, JavaScript walks up the scope chain: first its own scope, then middle, then outer, until it finds each variable.

Practical Example

function makeCounter(start) {
  let count = start;
  
  return function() {
    count++;
    
    return function getCount() {
      return count;
    };
  };
}

const counter = makeCounter(0);
const getFirst = counter();
const getSecond = counter();

console.log(getFirst());  // 1
console.log(getSecond()); // 2

Each level preserves access to the variables above it, no matter how many layers you nest.

Key Takeaway: Nested closures form a chain through all enclosing lexical environments, allowing inner functions to access variables from every outer scope they're defined within.