A closure in JavaScript is the combination of a function bundled together (enclosed) with references to its surrounding state, known as the lexical environment.
In simpler terms:
- A closure allows an inner function to access the variables and parameters of its outer (enclosing) function, even after the outer function has finished executing and its execution context has supposedly closed.
- Closures are created every time a function is created in JavaScript, at function creation time.

ES6 syntax and closures
With ES6, closures can be created using arrow functions, which provide a more concise syntax and lexically bind the this value. Here's an example:

Closures in React
Closures are everywhere. Below code shows a simple example of increasing a counter on a button click. In this code, handleClick forms a closure. It has access to it's outer scope variable count and setCount

How closures work:
- Lexical scoping: JavaScript uses lexical scoping, meaning a function's access to variables is determined by its actual location within the source code.
- Function creation: When a function is created, it keeps a reference to its lexical scope. This scope contains all the local variables that were in-scope at the time the closure was created.
- Maintaining state: Closures are often used to maintain state in a secure way because the variables captured by the closure are not accessible outside the function.
Why use closures?
Using closures provide the following benefits:
- Data encapsulation: Closures provide a way to create private variables and functions that can't be accessed from outside the closure. This is useful for hiding implementation details and maintaining state in an encapsulated way.
- Functional programming: Closures are fundamental in functional programming paradigms, where they are used to create functions that can be passed around and invoked later, retaining access to the scope in which they were created, e.g. partial applications or currying.
- Event handlers and callbacks: In JavaScript, closures are often used in event handlers and callbacks to maintain state or access variables that were in scope when the handler or callback was defined.
- Module patterns: Closures enable the module patternin JavaScript, allowing the creation of modules with private and public parts.