DEV Community

Cover image for Comprehending Closure in JavaScript: A Frequently Asked Interview Question 🚀🔥
Arjun Vijay Prakash
Arjun Vijay Prakash

Posted on • Updated on

Comprehending Closure in JavaScript: A Frequently Asked Interview Question 🚀🔥

💭 Introduction

Throughout the interview, the interviewer may inquire about the concept of closure to assess your proficiency as a JavaScript developer.

This article encompasses the following topics:

  1. The definition of closure.
  2. The benefits associated with closure.
  3. A specific interview question regarding closure.
  4. Strategies for effectively answering the question.

Before delving into these details, it is crucial to familiarise yourself with JavaScript scope, particularly lexical scoping. To gain a comprehensive understanding of these concepts. It is essential to grasp these concepts before delving into the topic of closure.

❓ What is Closure?

"A closure gives you access to an outer function's scope from an inner function."

or you can also say

"A closure is the combination of a function bundled together with references to its surrounding state (the lexical environment)."
Example -

function outer() {
    let name = "John Doe";
    function inner() { // closure
        console.log(name);
    }
    inner();
}
outer(); // John Doe
Enter fullscreen mode Exit fullscreen mode

The provided code demonstrates the concept of closure as it involves accessing a variable from the outer function's scope within the inner function's scope.

In essence, the inner function is effectively encapsulated or "closed" within the outer function.

✅ Advantages of Closure

  1. Ability to Retain Data

    • Even after the execution of the outer function is completed, you can still access its variables through closure.
  2. Encapsulation of Data

    • By employing the closure module pattern, you can store multiple functions within an object and return them, achieving data encapsulation.
  3. Code Modularization

    • Modularization, a programming practice that involves eliminating repetitive code, can be facilitated using closure.

🚩 Interview Question

During an interview, you may encounter questions related to closure to evaluate your understanding of JavaScript.

Example Question: Write a code snippet that prints numbers from 1 to 5 after a delay of 3 seconds.

To address this question, your initial thought process could be as follows:

  • Initialize an array to store the numbers.
  • Utilize a for-loop to iterate through the array.
  • Implement setTimeout() function to print each element after a delay of 3 seconds.
function interviewQues() {
    for (var i = 1; i <= 5; i++) {
        setTimeout(function() {
            console.log(i);
        }, 3000);
    }
}
interviewQues();
Enter fullscreen mode Exit fullscreen mode

Image

Why does it print "6" five times?

When using the var keyword to declare "i" inside the interviewQues() function, its scope is limited to that function. Furthermore, setTimeout works asynchronously in JavaScript, meaning it executes after the synchronous part of the code has finished. While the interviewQues() function's scope remains the same throughout, the for-loop runs five times, incrementing "i" each time until it reaches a value of 6. After that, setTimeout() is triggered and prints "6" five times.

Image

To simply say it, it is due to var i.

🔑 How to Answer

There are two possible solutions to this problem:

  • Employ a closure and IIFE (Immediately Invoked Function Expression).
  • Replace the var keyword with let.

One approach to solving this is by utilising a closure:

function interviewQues() {
    for (let i = 1; i <= 5; i++) {
        (function(j){ // IIFE declaration
            setTimeout(function() {
                console.log(j);
            }, 1000);
        })(i); // IIFE call
    }
}
interviewQues();
Enter fullscreen mode Exit fullscreen mode

To address the question, I implemented the concept of closure, which involves the relationship between the inner function and the outer function or variable, along with the utilization of IIFE (Immediately Invoked Function Expression).

In an IIFE, the function declaration and invocation occur simultaneously, ensuring immediate execution of the function.

By passing the variable "i" as a parameter to "j" within the IIFE, the value of "j" will be printed after a delay of 3 seconds.

Additionally, an alternative approach to solve the question was to replace the "var" keyword with "let".

function interviewQues() {
    for (let i = 1; i <= 5; i++) { 
        setTimeout(function() {
            console.log(i);
        }, 3000);
    }
}
interviewQues();
Enter fullscreen mode Exit fullscreen mode

To achieve the desired outcome, simply replace "var" with "let".

How does this solution work? When "var" is used, "i" is confined to the scope of the interviewQues() function, allowing it to hold only one value at a time. However, by using "let", "i" becomes scoped within the for-loop, resulting in five separate scopes (depending on the number of iterations). As a result, you can successfully print the numbers 1, 2, 3, 4, and 5 instead of repeating the number 6 five times.

I have always been deeply passionate about writing, and nothing brings me more joy than offering assistance and inspiration to others. If you have any inquiries or require any guidance, please don't hesitate to contact me. I am here to help!

My Instagram - @arjuncoder
My Github - @CoderPOOP
My Twitter - @arjuncodess

Top comments (0)