Docs

Namaste JavaScript — Interview Quick Notes

Ep 10–12: Closures


  • A closure = a function bundled together with its lexical scope. The function remembers variables from its outer scope even after the outer function has returned.
  • Closures enable: module pattern, currying, memoisation, data hiding/encapsulation, setTimeout callbacks.
  • Downside: closed-over variables are not garbage-collected until the closure itself is released → potential memory leaks.
  • Classic Q — var in loop: all closures share the same i reference → prints 6,6,6,6,6. Fix: use let (block-scoped) or wrap with IIFE to capture a new copy.
1function counter() { 2 var count = 0 3 return function increment() { 4 count++ 5 console.log(count) 6 } 7} 8const c1 = counter() 9c1() // 1 10c1() // 2 11 12// var in loop — prints 6,6,6,6,6 13for (var i = 1; i <= 5; i++) { 14 setTimeout(() => console.log(i), i * 1000) 15} 16 17// Fix: use let 18for (let i = 1; i <= 5; i++) { 19 setTimeout(() => console.log(i), i * 1000) 20}