Sunday, 2 March 2025

Quick Introduction to Closures in JavaScript: A Step-by-Step Guide

In JavaScript, a closure is a feature where an inner function has access to the variables of its outer (enclosing) function, even after that outer function has finished executing. Essentially, a closure allows a function to "remember" the environment (or scope) in which it was created.

hello-world.js 

function outerFunction() {
  let outerVariable = "I am defined at Outer Layer Scope";

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

const myClosure = outerFunction();
myClosure(); // Output: "I am defined at Outer Layer Scope"

 Output

I am defined at Outer Layer Scope

 

When outerFunction is called and returns innerFunction, we assign that returned function to myClosure. Even though outerFunction has finished executing, myClosure (which is innerFunction) still remembers the environment it was created in, which includes the outerVariable.

 

How Do Closures Retain Access to the Outer Scope?

This behaviour is possible because of JavaScript's lexical scoping. JavaScript functions are lexically scoped, meaning they remember the scope in which they were created. When innerFunction is created, it has access to outerFunction's scope, including variables declared within outerFunction.

 

When you call a function that creates and returns a closure, a new function instance is created each time, even if the code inside is the same. This is because each call to the outer function creates a new scope with its own set of variables, and the inner function (the closure) captures and retains access to that specific scope.

 

diff-inner-function-on-each-call.js

function outerFunction(name) {
  let count = 0;

  function innerFunction(name) {
    count++;
    console.log(`Closure : ${name}, Count is ${count}`);
  }

  return () => innerFunction(name);
}

const myClosure1 = outerFunction("Closure1");
const myClosure2 = outerFunction("Closure2");

myClosure1();
myClosure2();

myClosure1();
myClosure2();

myClosure1();
myClosure2();

 

Output

Closure : Closure1, Count is 1
Closure : Closure2, Count is 1
Closure : Closure1, Count is 2
Closure : Closure2, Count is 2
Closure : Closure1, Count is 3
Closure : Closure2, Count is 3

 Each Call to outerFunction Creates a New Execution Context, When you call outerFunction, it creates a new execution context (a new scope) with its own local variables. This includes the count variable, which is initialized to 0 each time.

 


Previous                                                    Next                                                    Home

No comments:

Post a Comment