Hiprup

What are closures in JavaScript?

A closure is a function that remembers and keeps access to variables from the scope where it was created, even after that outer scope has finished running.

They work because a function holds a reference to its surrounding scope, not a copy. Common uses:

  • Private state — hide data so only the inner function can read or change it.

  • Function factories — build customised functions that share preset values.

  • Callbacks & handlers — remember context for later asynchronous calls.

Interview classic: a var loop with setTimeout logs the final value repeatedly because every callback shares one variable — let gives each iteration its own copy.

createCounter returns functions that close over count — count persists between calls but is inaccessible from outside (private). createMultiplier returns functions with different factor values captured. The loop problem: var i is shared, all callbacks see the final value 3.

IIFE creates a new scope per iteration. let creates a new binding per iteration (cleanest fix).

The loop+setTimeout problem is the #1 closure interview question. Show the bug (var, all print 3), explain why (shared variable), and show two fixes (IIFE and let).

The counter example for data privacy shows practical use.

What are closures in JavaScript? | Hiprup