🧭Closure
Also known as Closures, Lexical Closure
A function that keeps the variables near it. It still has them later.
Think of it like
Think of it like a backpack. The function takes it along and keeps what was packed inside.
Example
Emma makes a counter. She calls it twice, and it says 2, because it kept its own count between calls.
Why it matters
Closures sit behind callbacks, event handlers and React hooks. They explain why a function sees a value you thought was gone.
Definition
Example code
python
def counter():
n = 0
def step():
nonlocal n
n += 1
return n
return step
c = counter()
c()
print(c()) # 2Common mistake
Key takeaways
- 1Remembers its birthplace. Keeps the outer variables.
- 2Lives on. After the outer code ends.
- 3Private state. Without a class.