Scope decides where a name is visible, and a closure is what happens when a function remembers the scope that it was created in. Together they explain why a callback still has access to a variable long after the function that owned it has finished, and why a tiny factory function can give you a piece of state that nothing else is able to touch.
The previous lesson in this module covered "Default Parameters, Rest and Function Tricks", and this lesson is the last one in the JavaScript Functions module.
What are the levels of scope in JavaScript?
There are three, and they sit inside each other. The global scope holds the top-level variables of your script. A function scope is created every time a function runs. A block scope is created by any pair of curly braces, so that means a function body, an if, a for, or a plain block of code.
const globalScope = 'global';
function outer() {
const functionScope = 'function';
if (true) {
const blockScope = 'block';
console.log('inside the block:', blockScope);
console.log('inside the block:', functionScope);
console.log('inside the block:', globalScope);
}
try {
console.log(blockScope);
} catch (error) {
console.log('caught:', error.constructor.name);
}
}
outer();
Inside the if block, all three names are visible. Outside it, blockScope is gone, and reading it throws a ReferenceError. The function scope and the global scope are still there, because the block sits inside the function, and the function sits inside the global scope.
That nesting is the rule that answers every question about scope: an inner scope can see an outer scope, and an outer scope cannot see an inner one. A name is visible from the point where it was declared until the end of the block that declared it.
What happens when two scopes use the same name?
The inner one wins, and it hides the outer one for as long as the inner scope lasts. This is perfectly legal and it is occasionally useful, but it is also the source of the classic bug where you change a variable and the wrong one changes.
const name = 'global';
function shadow() {
const name = 'local';
return name;
}
console.log('the function gives', shadow());
console.log('the outer value is still', name);
Renaming the inner variable to something more specific, such as label instead of name, removes the ambiguity completely. When you find yourself tempted to hide a name, rename it instead.
What is the temporal dead zone, exactly?
A let or a const binding exists from the start of its block, but it has no value until its declaration runs. The gap between those two moments is the temporal dead zone, and using the name inside it throws a ReferenceError.
try {
console.log(later);
let later = 'never reached';
} catch (error) {
console.log('caught:', error.constructor.name, '-', error.message);
}
The message says Cannot access 'later' before initialization. This is why you cannot call a function that uses a const before that const has been given its value, even though the function itself is perfectly valid. It is also exactly what makes const a stronger guarantee than var, where the same mistake would quietly give you undefined instead of an error.
What is a closure?
A closure is a function together with the scope that it was created in. When you create a function inside another function, the inner function keeps a reference to the variables of the outer function, and it keeps that reference even after the outer function has returned.
function createCounter() {
let count = 0;
return function increment() {
count += 1;
return count;
};
}
const counter = createCounter();
console.log('first call gives', counter());
console.log('second call gives', counter());
console.log('third call gives', counter());
const other = createCounter();
console.log('a new counter starts at', other());
Read that carefully. createCounter has finished running, and count no longer exists anywhere that you can reach it. Even so, counter() still increments it and still reports the running total. Every call to createCounter produces a fresh count, which is why other() starts at 1 again.
The variable is not hidden by magic. It is simply that no name outside the closure refers to it, so nothing else is able to change it. The closure holds the only reference.
What are closures actually good for?
Keeping state private. A closure lets you expose some operations without exposing the data that they work on, and you do not need a class to do it.
function createBankAccount(owner) {
let balance = 0;
return {
deposit(amount) {
balance += amount;
return balance;
},
getBalance() {
return balance;
},
ownerName() {
return owner;
},
};
}
const account = createBankAccount('Ada');
account.deposit(500);
console.log('the balance is', account.getBalance());
console.log('the balance is not exposed:', account.balance);
console.log('the owner is', account.ownerName());
The balance variable is unreachable from outside. The only way to change it is through deposit, and the only way to read it is through getBalance. That is encapsulation without a single class, and it is the same mechanism that powers the module pattern, private counters, remembered results, and a surprising amount of the library code that you already use.
Another everyday use is attaching context to a callback. A closure lets you hand a function a piece of information that it should carry with it, without that information having to be a parameter that is passed at call time.
function attachLabel(prefix) {
return function log(message) {
return '[' + prefix + '] ' + message;
};
}
const warn = attachLabel('warn');
console.log(warn('disk almost full'));
console.log(warn('retrying'));
What are the closure pitfalls?
There are two, and both of them are about lifetimes rather than about syntax.
The first one is memory retention. A closure keeps its captured variables alive for as long as the closure itself can be reached. If you create a closure inside a loop and store it in an array, then every captured value stays alive too. That is usually what you want, and it is occasionally a leak in a long-running page.
function makeHandlers(items) {
const handlers = [];
for (const item of items) {
handlers.push(() => item);
}
return handlers;
}
const handlers = makeHandlers(['a', 'b', 'c']);
const results = [];
for (const handler of handlers) {
results.push(handler());
}
console.log('the handlers give', results);
console.log('there are', handlers.length, 'of them');
The second one is shared state. When two closures capture the same variable, they share it. Two handlers that come from the same factory can interfere with each other, and the bug only shows up when both of them are used together. When a factory returns something that is meant to be used once, make that clear in the name, with createCounter rather than counter.
One more trap is worth naming. Creating a closure inside a loop that captures the loop variable behaves differently depending on how the loop was written. The let version of a classic for loop gives each round its own binding, while the var version shares one. The variables module of this tutorial covers that difference in full.
The scope and closure rules to remember
- Scopes nest, so you have the global scope, then the function scope, then the block scope. An inner scope can read an outer name, and an outer scope cannot read an inner one.
- Declaring a name inside a block hides the outer one for the length of that block, so rename rather than hide.
- A
letor aconstis in its temporal dead zone until its declaration runs, and using it earlier throws an error. - A closure is a function plus the scope it was created in, and it keeps that scope alive after the outer function returns.
- Closures give you private state without classes, because you expose the functions and hide the variable.
- Closures capture values, so two closures over the same variable share it.
Try it yourself: build a createPlaylist() factory that returns an object with add, remove, next, and list, where the playlist itself lives inside a closure and nothing outside can reach it. Then call createPlaylist() twice and confirm that the two playlists are completely independent. Finally, try to read the internal list directly and watch the undefined tell you that the state really is private.