What is a Closure in JavaScript

A closure isn't a concept to memorize. It's something your code is already doing. Most developers hear the word "closure" and immediately feel behind. They're not. They've been writing closures since day one. Take a look at the image below. That inner function has no variable of its own — but it remembers the one from the outer scope, even after the outer function has finished running. Not a copy. A live reference. Which is why the value keeps updating across calls instead of resetting to zero. That's the whole mechanism. That's a closure. You've already used this pattern without knowing the name: → Debounce and throttle utilities → Event handlers that track state between calls → React's useState — built on this exact idea The concept was never the hard part. The word made it sound harder than it is. Once you see it — you'll start spotting closures in code you wrote years ago. #JavaScript #WebDev #FrontendDevelopment #ReactJS #Programming

  • js, javascript, closures, webdev
Martin Weiser

Staff / Principal Fullstack Engineer | Building Scalable Web and Mobile Solutions

3w

It would be more useful to mention closure always together with the scope chain.

If you’re inadvertibly relying on closures without knowing what their name or implication is, maybe it’s time to grow a pair of eyes and read the 101 of JavaScript.

Closures and generators are often confused, but this example explains the difference really well 👍

I’m probably wrong on this, but I feel like closures are just OOP with extra steps.

See more comments

To view or add a comment, sign in

Explore content categories