Scope and closures, gently
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
What scope means
Scope is the area of code where a variable can be seen. A variable you declare inside a function is invisible outside it. This is a feature. It stops different parts of your program from stepping on each other.
JavaScript has three levels you need to know about: global, function and block.
Global scope
A variable declared outside any function or block is global. Every part of the program can read it.
const siteName = "HussoTech";
function showSite() {
console.log(siteName); // can see it
}
showSite();
Globals are convenient and dangerous. Any code can change them, so when something goes wrong you have a lot of places to search. I keep globals to a minimum.
Function scope
Variables declared inside a function exist only while the function runs.
function calculate() {
const result = 10 * 5;
return result;
}
console.log(calculate()); // 50
// console.log(result); // ReferenceError: result is not defined
Each call gets a fresh set of local variables. Two calls to the same function do not share them.
Block scope
A block is any code inside curly braces: an if, a for loop or just { }. Variables declared with let and const live only inside their block.
let message = "outer";
if (true) {
let message = "inner"; // a different variable
console.log(message); // "inner"
}
console.log(message); // "outer"
for (let i = 0; i < 3; i++) {
// i exists only here
}
// console.log(i); // ReferenceError
The inner message hides, or shadows, the outer one for the length of the block. Shadowing is legal but confusing. I avoid reusing names in nested scopes.
This is the main reason to avoid var. It ignores block scope and is only limited by functions, so a var declared inside an if is visible after it. That surprises people and causes bugs.
The scope chain
When code uses a name, JavaScript looks in the current scope. If it is not there, it looks in the surrounding scope, then the next, until the global one. Inner code can read outer variables. Outer code cannot read inner ones.
const tax = 0.17;
function priceWithTax(price) {
const total = price + price * tax; // tax comes from outside
return total;
}
console.log(priceWithTax(100)); // 117
Closures
Now the interesting part. A function remembers the variables from the scope where it was created, even after that outer scope has finished. This remembered environment is called a closure.
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counterA = createCounter();
const counterB = createCounter();
console.log(counterA()); // 1
console.log(counterA()); // 2
console.log(counterA()); // 3
console.log(counterB()); // 1, separate counter
Walk through it. Calling createCounter() creates a variable count and returns an inner function. Normally count would vanish when createCounter finishes. But the inner function still uses it, so JavaScript keeps it alive. Each call to createCounter makes its own count, which is why counterB starts again from 1.
From the outside, nobody can touch count directly. The only way to change it is through the function. That gives you private data, with no classes needed.
A practical use: configurable functions
Closures let you build functions that are pre-set with some value:
function makeMultiplier(factor) {
return n => n * factor;
}
const double = makeMultiplier(2);
const triple = makeMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
double remembers that factor was 2. This pattern shows up in event handlers, API helpers and many libraries.
The loop trap
Closures explain a famous bug with var:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
// prints 3, 3, 3
All three callbacks share the one i, which is 3 by the time they run. With let, each round of the loop gets its own i, and the output is 0, 1, 2:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
Common mistakes
- Declaring a variable inside a block and using it outside. You get a ReferenceError.
- Relying on globals. Pass values as parameters instead.
- Shadowing by accident. Using the same name in an inner scope hides the outer one.
- Using var in loops with callbacks. Use
let. - Thinking closures copy values. They keep access to the variable itself, not a snapshot. If the variable changes, the closure sees the new value.
Try it yourself
- Write
createGreeter(greeting)that returns a function taking a name and returninggreeting + ", " + name. - Extend the counter so it returns an object with
increment(),decrement()andvalue()methods that share one private count. - Predict the output of the
varloop withsetTimeout, then fix it two ways. - Write a function
once(fn)that runsfnonly the first time it is called, using a closure variable.
let message = "outer";
if (true) {
let message = "inner"; // a different variable
console.log(message); // "inner"
}
console.log(message); // "outer"
for (let i = 0; i < 3; i++) {
// i exists only here
}
// console.log(i); // ReferenceError
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account