Scope Chain & Closures

Master the invisible boundaries of JavaScript. Learn how variables are protected and how functions remember the world they were born in.

JavaScript8 min readConcept 14 of 62

Scope & The Scope Chain

Scope determines the visibility of variables. If you declare a variable inside a function, it is 'scoped' to that function and cannot be seen from the outside.

However, inner functions *can* look outward. If a variable isn't found locally, JavaScript looks up the 'Scope Chain' to the parent function, and keeps looking until it hits the global scope.

What is a Closure?

A closure is a feature where an inner function 'remembers' the variables from its outer scope, even after the outer function has finished running.

When a function returns another function, the returned function carries a 'backpack' containing all the variables it needs from its birthplace.

Creating private state

Closures are the secret to creating private data in JavaScript. If you have a createCounter() function that defines a count variable and returns an inner function that increments it...

The outer function finishes, but the inner function still has exclusive access to count in its closure backpack. Nothing else in your entire program can touch that count variable directly!

The Closure Counter

Create a counter factory and watch how the inner function retains access to the private count state across multiple separate executions.

The Closure Counter

function createCounter() {
Closure State
let count = 0;
return function() {
count++;
return count;
}
}
// 1. Create the counter (sets count to 0)
const myCounter = createCounter();
// 2. Call the inner function multiple times
console.log(myCounter());
Console OutputState Preserved
(Click the button to call myCounter)
iThe createCounter function has already finished running, yet the returned function still remembers the count variable perfectly!

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What is the Scope Chain?
  2. 2Which statement best describes a Closure?
  3. 3Why are closures useful for creating private variables?

Remember this

  • Lexical scope means physical placement in the code dictates variable access.
  • Inner functions can look outward (Scope Chain), but outer functions cannot look inward.
  • A closure is an inner function that 'remembers' its outer variables even after the outer function finishes.
  • Closures are the primary mechanism for achieving data privacy in JavaScript.

Done with this concept?

Mark it complete to track your progress. No login needed.