Closures in JavaScript

A Closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.

The closure has three scope chains:

  • It has access to its own scope — variables defined between its curly brackets.
  • It has access to the outer function’s variables.
  • It has access to global variables.

Some Examples Using Closures:

size12, size14, and size16 are now functions that resize the body text to 12, 14, and 16 pixels, respectively.