JavaScript Closures β
Imagine a library in JavaScript.
- ποΈ Outer function = the library
- π Inner function = a book
- π Variable = a secret note inside the library
- π Closure = the book carrying the secret note with it
π The Story
Suppose we create a function called outer():
function outer() {
let secret = "Hello JavaScript!";function inner() {
console.log(secret);
} return inner;
}const myFunction = outer();myFunction();
π§ What happens?
Step 1: outer() creates the variable secret.
Step 2: Inside it, inner() is created.
Step 3: outer() returns inner.
Step 4: Even though outer() has finished, inner() remembers secret.
Get Raveenanagarβs stories inΒ yourΒ inbox
Join Medium for free to get updates fromΒ thisΒ writer.
So:
outer()
β
βββ secret = "Hello JavaScript!"
β
βββ inner()
β
βββ remembers secret πWhen we call:
myFunction();the output is:
Hello JavaScript!π The Easy Definition
A closure is a function that remembers and can access variables from its outer scope even after the outer function has finished executing.
π’ A Real-Life Example: Counter
function createCounter() {
let count = 0;return function () {
count++;
return count;
};
}const counter = createCounter();console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Why does count remember its value?
Because the returned function forms a closure around count.
β Remember It Like This
Outer Function
β
creates variable
β
Inner Function
β
remembers variable
β
CLOSURE πOne-line exam definition:
Closure = Function + its remembered lexical environment.









