JavaScript closures


A closure can be defined as a JavaScript feature in which the inner function has access to the outer function variable. In JavaScript, every time a closure is created with the creation of a function.

The closure has three scope chains listed as follows:

  • Access to its own scope.
  • Access to the variables of the outer function.
  • Access to the global variables.

Example -

Closure points the variable and stores the reference of a variable. They don't remember the variable's value. In the above code, we are updating the function closure() argument with every call. So, we will get the different values of the variable i, at different index.

Closures are one of the slightly difficult to understand concept of JavaScript, but try to practice the closure in different scenarios like to create callbacks, getters/setter.