JavaScript Tutorial · Functions · Lesson 21 of 44
JavaScript Scope and Closures
Block scope, function scope and how closures remember variables.
Scope
Scope decides where a variable is visible.
- Variables declared with
let/constinside{ }are block-scoped. - Variables declared inside a function are visible only inside that function.
- Inner code can read variables from outer scopes, but not the other way round.
const site = "ReadyCamel"; // global scope
function show() {
const page = "Scope"; // function scope
if (true) {
const note = "block only"; // block scope
console.log(site, page, note);
}
console.log(typeof note);
}
show();
console.log(typeof page);
Output
ReadyCamel Scope block only undefined undefined
Closures
A closure is a function that remembers the variables from where it was created — even after that outer function has returned. Closures are how JavaScript gives you private state:
function makeCounter() {
let count = 0; // private: only the returned functions can see it
return {
increment: () => ++count,
current: () => count,
};
}
const a = makeCounter();
const b = makeCounter();
a.increment();
a.increment();
b.increment();
console.log(a.current(), b.current());
Output
2 1
Closures in practice
Function factories, event handlers and debouncing all use closures:
function multiplier(factor) {
return (n) => n * factor;
}
const double = multiplier(2);
const triple = multiplier(3);
console.log(double(10), triple(10));
Output
20 30
Closures and loops are a favourite interview question — try var vs let in closures.
Test yourself
What is a closure?
A function with no parametersA function that remembers variables from the scope where it was createdA way to close a browser windowA function that has finished running
Show answer
Answer: A function that remembers variables from the scope where it was created
Practice next
- Implement debounce() · coding problem
- var in a Loop with setTimeout · coding problem