All tutorials
Advanced

Closures

Inner functions remember the variables of their outer scope.

1. Explanation

A closure is created when a function 'closes over' variables from its outer scope and keeps access to them even after the outer function has finished running. Closures power data privacy, function factories, and event handlers.

2. Example

Try it yourself
Console
Click Run to see output.

3. Expected output

output
1
2
3

4. Common mistakes

  • Creating closures inside loops with var (all share the same variable) — use let
  • Holding large objects in closures and leaking memory
  • Expecting the closed-over variable to be a snapshot — it's live

5. Practice questions

  1. Write an 'add(x)(y)' currying function
  2. Build a private 'bank account' with deposit/withdraw using closures
  3. Create a function that limits how many times another function can be called
→ Try more practice problems