Closures Explained in minutes (🎒 Backpack Analogy)
dev.to¡6h¡
Discuss: DEV
Flag this post

Ever wondered why some functions “remember” things even after they should’ve been forgotten?

Like:

“How does this function still know that variable?!” 🤯

Congratulations — you just met one of JavaScript’s most powerful (and confusing) features:

Closures

Let’s break it down super simply. No CS degree needed.


🎒 Think of a Function as a Person with a Backpack

When a function runs, it’s like a person going on a trip.

Before they leave, they pack a backpack with everything they might need:

  • Variables from their current location
  • Variables from their parent’s house (outer function)
  • Even grandparents’ stuff if needed

That backpack? That’s a closure.

The function carries it everywhere, even after leaving home.


Example: Leaving Home But Keep…

Similar Posts

Loading similar posts...