Scope & Closures
Understand block scope with const/let, lexical scope, and how closures let functions remember private state safely.
What you'll learn
- Distinguish global, function, and block scope ({ ... })
- Understand how closures capture variables from their outer function
- Build factory functions with encapsulated private state
Scope controls where a variable can be accessed. const and let are block-scoped, they only exist inside the nearest { ... } block (like an if statement or for loop).
What Is a Closure?
A closure is created whenever an inner function references variables from its outer function, even after the outer function has finished running!
function createCounter(start = 0) {
let count = start; // private to this closure!
return () => {
count += 1;
return count;
};
}
const nextId = createCounter(100);
nextId(); // 101
nextId(); // 102
Fill-in-the-Blank Exercise
Closure Factory Function
Return an inner arrow function that remembers the multiplier parameter.
function makeMultiplier(factor) {
(value) => value * ;
}
const double = makeMultiplier(2);Try It Yourself
Notice how each counter button maintains its own completely independent private count via a closure:
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
1. What makes a closure special in JavaScript?
Finished this lesson?
Your progress is saved locally in your browser, no account needed.