01 / 20

Scope &
Closures

Master how JavaScript organizes variables, controls access, and enables powerful patterns through closures.

JavaScript

What Is Scope?

Scope determines where in your code a variable can be accessed. Think of it as a set of rules that governs how the JavaScript engine looks up variable names at any given point during execution.

Visibility
Which parts of your code can "see" a variable
Lifetime
How long a variable stays in memory
Isolation
Prevents variables from clashing with each other

The Three Types of Scope

Global Scope let theme = "dark" Function Scope function greet() { let name = "Ada" } Block Scope if (true) { let x = 10 } let and const are block-scoped Outer scopes contain inner scopes nesting

Why Scope Matters

Scope is not just an abstract concept: it directly impacts how you write, debug, and organize real JavaScript code every day.

1
Prevents naming collisions: Two functions can each have a local variable called count without interfering with each other.
2
Enables data privacy: Variables inside a function are hidden from the outside world: a key ingredient of closures.
3
Helps garbage collection: When a scope is no longer reachable, its variables can be freed from memory automatically.

The Scope Chain

When JavaScript encounters a variable name, it searches for it in the current scope first, then walks outward through each enclosing scope until it finds a match or reaches the global scope.

Global Scope Outer Function Inner Function looks up looks up ReferenceError if not found anywhere

The Core Rule: Lexical Scope

This is called lexical (or static) scoping. The word "lexical" means "relating to the text": the engine reads the nesting structure of your code to decide which variables each function can access.

const x = 10; function outer() { const y = 20; function inner() { console.log(x + y); // 30 } inner(); }

var vs let vs const

var let const
Scope Function Block Block
Hoisted? Yes (as undefined) Yes (TDZ) Yes (TDZ)
Re-assignable? Yes Yes No
Re-declarable? Yes No No
Best practice Avoid Default Prefer

What Is a Closure?

When a function is defined inside another function and is then returned or passed elsewhere, it carries a hidden reference to its original scope. That "backpack" of variables is the closure.

Function
The inner function itself
Environment
The saved scope variables it "closes over"

How Closures Work

makeCounter() let count = 0 function increment() count++ return count return counter (returned) counter() → 1 counter() → 2 counter() → 3 Closure "backpack" count: lives on! makeCounter() has finished executing count persists via closure

How to Recognize a Closure

1
Find a nested function: a function defined inside another function.
2
Check for "free variables": variables the inner function uses but did not declare itself.
3
Verify the inner function escapes: it is returned, passed as a callback, or stored somewhere outside its parent.
4
If all three are true: you have a closure. The free variables will persist as long as the inner function exists.

Example 1: Basic Closure

function makeGreeter(greeting) { return function(name) { return greeting + ", " + name; }; } const hello = makeGreeter("Hello"); const hola = makeGreeter("Hola"); console.log(hello("Ada")); // "Hello, Ada" console.log(hola("Ada")); // "Hola, Ada"

Example 2: Private Counter

function makeCounter() { let count = 0; // private variable return { increment() { count++; return count; }, decrement() { count--; return count; }, getCount() { return count; } }; } const c = makeCounter(); c.increment(); // 1 c.increment(); // 2 c.decrement(); // 1

Example 3: The Loop Trap

// BUG: prints "3" three times for (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); } // FIX: prints 0, 1, 2 for (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100); }

Common Mistakes

✕ var in Loops
Using var in a for-loop and expecting each callback to capture a unique value. Use let instead.
✕ Accidental Globals
Forgetting let/const/var before a variable name creates a global variable, leaking data everywhere.
✕ Memory Leaks
Closures keep their scope alive. If a closure holds a reference to a large object you no longer need, it cannot be garbage-collected.

Scope & Closures Summary

Concept What It Is Key Behavior
Global Scope Outermost level Accessible everywhere
Function Scope Inside a function var lives here
Block Scope Inside { } let/const live here
Scope Chain Lookup mechanism Inner → Outer → Global
Closure Function + environment Remembers outer vars
Lexical Scope Scope by position Defined at write-time

Question 1 of 5

In JavaScript, scope is best described as:

Question 2 of 5

What does console.log(reveal()) output?

Question 3 of 5

What is logged to the console?

Question 4 of 5

What does "lexical scope" mean?

Question 5 of 5

A closure captures a variable by: