How do JavaScript closures work

Closures in JavaScript is a feature where an inner function has access to the outer function’s variables. In many programming languages, the variables in scope are limited to global variables, parameters, and local variables. In languages which support closures , such as JavaScript, variables may also be bound dependent on the context in which a function was declared.

JavaScript closure has three scope:

  1. Access to its own scope, i.e., the variable defined within its curly braces.
  2. Access to the variables of the outer functions.
  3. Access to the global variables.
This is usually done using nested functions where the outer function exits and either returns a function, or declares a function which outlives it. This inner function then has references to the variables and parameters declared within the outer function , even though those variables are no longer in scope. example
const countDown = (function () { let counter = 5; return function () { counter -= 1; console.log(counter); return counter } })(); countDown(); countDown(); countDown(); countDown();
4 3 2 1
In the above code, the variable "countDown" is assigned to the return value of a self-invoking function. The self-invoking function only runs once. It sets the counter to five (5), and returns a function expression . This way "countDown" becomes a function. The interesting part is that it can access the counter in the parent scope. This is called a JavaScript closure . It makes it possible for a function to have "private" variables. The counter is protected by the scope of the anonymous function, and can only be changed using the countDown function.
Javascript closures
JavaScript closures make code more compact, readable and beautiful and promote functional reuse. It has many useful applications, such as currying, simulating private data , and greatly reducing the need for global variables.