JavaScript
/Intermediate
Closures
Definition
A closure is simply a function that remembers the variables around it, even after the function that created it has finished running.
Explain Like I'm New
Think of a closure like a function with a memory. Normally, when a function finishes, its variables are gone forever. But if you create a smaller function inside it, that smaller function remembers the variables from the first one. It packs them in a little invisible backpack so it can use them later.
Real World Example
Think of a smart lock. The lock remembers the password that was set when it was manufactured (outer environment). Even years later, when you try to open it (inner function), it still remembers that original password to check against.
Common Use Cases
- •Data privacy / Emulating private methods
- •Partial applications or currying
- •Event handlers and callbacks
- •Memoization
Interactive Example
Loading...
Console output will appear here...
Interview Questions
basic
- What is a closure in JavaScript?
- Can you give a simple example of a closure?
intermediate
- How do closures help with data encapsulation?
- What is the difference between scope and closure?
advanced
- How do closures affect memory management and garbage collection?
- What is the module pattern and how does it relate to closures?
trick
- What is the output of a loop with var and setTimeout, and how do closures fix it?
hr
- Tell me about a time you had a hard-to-find bug related to variable scoping.