What is Closure in JavaScript

A closure in JavaScript is a robust feature that allows a function access to its scope (i.e., variables defined within the function), the scope of an outer containing function, and global scope variables even after the outer containing function has finished executing.

This concept is beneficial for preserving state or creating private variables in JavaScript, as the language does not have built-in support for private variables like some other programming languages.

Closures are created every time a function is defined within another function. They are formed by combining an inner function and the environment (variables and their values) it has access.


function outerFunction() {
  const outerVar = 'I am an outer variable';

  function innerFunction() {

  return innerFunction;

const closureFunction = outerFunction();


I am an outer variable

In this example:

  1. The outerFunction defines a variable outerVar and a function innerFunction.
  2. The innerFunction has access to outerVar because it is defined in the same scope.
  3. The outerFunction returns innerFunction, which is assigned to the variable closureFunction.
  4. When we call closureFunction(), it logs the value of outerVar even though outerFunction has already finished executing. This is because innerFunction has access to the outerVar through the closure.

Closures are frequently used in JavaScript for various purposes, such as implementing private variables, creating function factories, and controlling the execution of asynchronous operations.

That’s it.

1 thought on “What is Closure in JavaScript”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.