Closure
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
How 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.
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.