What are JavaScript closures and how do they function?

I’m trying to wrap my head around JavaScript closures but I’m having trouble understanding how they actually work. I know about functions and variables and basic programming concepts, but closures just don’t click for me yet.

I’ve read some explanations online but they’re either too technical or use examples that don’t make sense to me. Can someone explain closures in simple terms? Maybe with a practical example that shows why they’re useful?

I understand that closures have something to do with functions accessing variables from their outer scope, but I don’t get how this works in practice or why it’s important. What makes a closure different from a regular function? When would I actually use one in my code?

Any help would be appreciated because I keep running into this concept and I feel like I’m missing something fundamental about how JavaScript works.

think of closures like a backpack your functions carry around. when you create a function inside another function, the inner one grabs all the variables it needs from the outer scope and takes them along for the ride. even after the outer function finishes, the inner still has its backpack with those vars. super useful for timers or keeping data private.

Closures are essentially functions that retain access to their enclosing scope, capturing variables at the moment they’re created. When you define a function within another function, the inner function maintains a reference to the outer function’s variables, which persist even after the outer function has completed execution. I encountered this concept while developing a simple game where each level kept track of the score independently. Using closures allowed me to encapsulate scores without exposing them globally. Each invocation of the outer function generates a new closure and its own set of variables, making it particularly useful for cases like creating custom functions or implementing private data.

Closures are functions that remember their surrounding context. When you create a function inside another function, the inner one keeps access to the outer function’s variables - even after the outer function finishes running. JavaScript wraps those variables in a closure. Here’s a simple example: a counter function that returns another function. The inner function can still increment and read the counter variable after the outer function has already executed. This lets you create private variables that can’t be accessed from outside. I use closures all the time for modules or keeping state between function calls. You’ll also see them in event handlers and callbacks. Once you know what to look for, you’ll realize you’ve been using closures without even knowing it. The key thing is that JavaScript functions carry their lexical scope with them - that’s what makes them different from most other programming languages.