What is a closure?
Learn how a function keeps accessing the variables of its defining scope.
What is a closure?
A closure is a function that remembers the variables from where it was created. Even after the outer function has finished, the inner function keeps accessing those outer variables. This happens because every JavaScript function carries its lexical environment with it.
For example, an outer function can declare let count = 0 and return an inner function. After the outer function ends, the inner one still reaches count.
Lexical environment
Every function stores a lexical environment reference to the scope where it was created. When the function runs, it looks up variables first in its own local scope, then in this stored scope.
That is why the outer function's local variable survives — the inner function holds a reference to it. This is exactly a closure: the bond between the captured variable and the function.
Exercise Build a greeter
Define a function called makeGreeter(message). It should return an inner function; when the inner function is called it should run console.log(message). Then call makeGreeter with a greeting string, assign the result to greet and invoke it with greet().
Show example solution
function makeGreeter(message) {
return function() {
console.log(message);
};
}
const greet = makeGreeter("Hello");
greet();
Test yourself
-
When does a closure capture a variable?
- From its defining scope, even after it ends
- Only from the scope at call time
- Only from the global scope
- From none, it uses only its own locals
Show answer
From its defining scope, even after it ends — Correct. A closure remembers its defining scope; it can reach that variable even after the outer function ends.
-
Complete the closure structure
function makeGreeter(message) { return ____() { console.log(message); }; }Show answer
function makeGreeter(message) { return function() { console.log(message); }; } -
Match the terms
- closure
- Remembers captured variables
- lexical environment
- Where it was defined
- captured variable
- Outer variable it accesses