Closure
Understand JavaScript closures - functions that remember variables from their outer scope even after execution completes, with practical examples and use cases
A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing.
Closure: Function + Remembering the variables from its outer function.
Use Case
-
To make private variables.
-
To keep data safe from being changed from outside.
Example
function outerFunction() {
let count = 0; // this variable lives inside outerFunction
function innerFunction() {
count = count + 1;
console.log(count);
}
return innerFunction;
}
const counter = outerFunction();
counter(); // prints 1
counter(); // prints 2
counter(); // prints 3How It Works
-
When
outerFunctionruns it creates a variable called count. -
Then it creates another function inside it called
innerFunction. -
Then it returns
innerFunction. -
When we call
outerFunctionwe getinnerFunctionback and store it in counter. -
Even though
outerFunctionhas finished running theinnerFunctionstill remembers count. -
So every time we call
counter(), it can still use and change count.
Difference Between Closure and Scope
- Scope means where a variable is available.
- Closure means when a function keeps using variables from another scope even after that scope is gone.
Important Points
-
Closure always remembers variable, not just value.
-
Each function call creates a new closure with its own memory.
-
varis function scoped, not block scoped.In loops with
var, all closures share the same variable. That is why setTimeout withvaroften prints the same number. -
letandconstare block scoped.In loops with let, every iteration gets a new variable. That is why setTimeout with let prints 0, 1, 2 correctly.
-
If two variables point to the same closure, they share the same memory.
const a = test(); const b = a;Both a and b use the same closure, so they share data.
-
Closures can keep variables alive even after the outer function is finished.
-
Understand scope chain.
If a variable is not found inside a function, JavaScript looks one level outside, then another, and so on, until it finds it. That chain is what makes closure possible.
JS in one word
Quick reference guide to JavaScript concepts explained in simple one-word definitions - closures, promises, hoisting, and 40+ essential JS terms
Hoisting
Master JavaScript hoisting - how variable and function declarations are moved to the top, differences between var/let/const, and the Temporal Dead Zone