Open In App

What are Closures in JavaScript ?

JavaScript closures involve the combination of functions and the scope in which they are defined. A closure allows a function to access variables from its scope, outer function scope, and the global scope. This creates a “closed-over” environment, preserving the state of the outer function even after it has finished executing.

Here’s a brief breakdown of closures:

  1. Scope Chain: In JavaScript, each function has access to its variables, as well as variables from all its ancestor scopes, creating a chain of scopes known as the “scope chain.
  2. Lexical Scoping: Closures are based on lexical scoping, which means that a function’s scope is determined by its position in the source code.
  3. Function Inside Function: When a function is defined inside another function, it forms a closure. The inner function has access to the outer function’s variables, even after the outer function has completed its execution.
Article Tags :