JavaScript Closures
JS
What is a closure?
A closure is created when a function “remembers” its outer scope, even after that outer function has finished executing. In other words:
- A closure is a combination of a function + the scope in which it was created.
This allows the function to access variables from its outer function scope even after the outer function has returned.
outer
runs and creates the variablename
.outer
returns theinner
function.greet
now holds the inner function.- When you call
greet()
, it still has access to name, even though outer has finished.
counter using closures
Closures are commonly used to remember state.
count
lives inside createCounter, butcounter()
still remembers it because of the closure.
Why closures are useful?
Data privacy:
Keep variables “private” and only accessible through functions.
Concept | Meaning |
---|---|
Closure | A function remembers the variables from the place where it was created, even after that scope is gone. |
Common uses | Data privacy, counters, factory functions, event handlers. |