What is a closure in JavaScript?
JavaScript Important







Closure
When we have a function nested inside another function. In that case, the child function will still have access to the outer function's scope, even after the outer(parent) function's execution context has been removed from the Execution stack.
Imagine you have a box (outer function) with a smaller box inside it (inner function). The inner box can "remember" and use anything that was in the outer box, even after the outer box is closed.
function createGreeting(name) { // This is our outer box
const message = "Hello, ";
return function() { // This is our inner box
console.log(message + name); // The inner box "remembers" message and name
}
}
const greetJohn = createGreeting("John");
greetJohn(); // Prints: "Hello, John"
Example Explanation
- The outer function
createGreeting
creates two things: the variablemessage
and thename
parameter - The inner function can use both
message
andname
, even aftercreateGreeting
has finished running - When we call
greetJohn()
, it still remembers both values
It's like when the inner function was created, it took a snapshot of all the variables it needed from its surroundings, and it keeps that snapshot for later use. This "remembering" behavior is what we call a closure.
00:00