[JavaScript] Understanding Closure - Common Interview Question

ยท

4 min read

[JavaScript] Understanding Closure - Common Interview Question

Introduction

During the interview, your interviewer can ask you some questions about the closure because they can know whether you are a good JavaScript developer or not.

In this article, we will cover:

  1. What is closure.

  2. Advantages of closure.

  3. An interview question about the closure.

  4. How to answer that question.

Before moving on, if you do not know about the scope in JavaScript, especially lexical scoping, check out this article: Mastering Scope

It is compulsory to understand those concepts before learning the 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

This code is an example of closure because you are accessing the variable that is in the outer function's scope from the inner function's scope.

Simply, the inner function is "closed" by the outer function.


Advantages of Closure

  1. Capable of keeping data

    • You can still access the variables of the outer function although the outer function is called and finished.
  2. Data encapsulation.

    • You can use the closure module pattern to store multiple functions in an object and return them.
  3. Modularization

    • Modularization in programming refers to organizing your code by eliminating repeating code. Closure can help with this.

๐Ÿšฉ Interview Question

Questions about Closure can appear during the interview to check your knowledge of JavaScript.

Question: Write a code that prints out numbers from 1 to 5 after 3 seconds.

How would you answer this question?

Your initial thought process would be like this:

  1. Create an array that stores the number

  2. Use for-loop to iterate through the array.

  3. Use setTimeout() to print the index after 3 seconds.

function interviewQues() {
    for (var i = 1; i <= 5; i++) {
        setTimeout(function() {
            console.log(i);
        }, 3000);
    }
}
interviewQues();

It prints out "6" 5 times, so why?

Declaring i with var keyword makes the i to be in the scope of interviewQues(). Moreover, setTimeout is the asynchronous JavaScript, so it is executed after the synchronous part is finished. The scope for interviewQues() is only one, on the other hand, the scope for the for-loop is 5 as it iterates 5 times. This means that the loop will run 5 times, after that, i holds a value of 6, then setTimeout() is executed.

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


How to Answer

There are two ways to solve this problem:

  1. Use a closure and IIFE to solve this.

  2. Change var to let.

Using a closure to solve:

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

I used the idea of a closure (relationship between the inner function and outer function (or variable) and IIFE (Immediately Invoked Function Expression) to solve answer the question.

In IIFE, function declaration and call happens at the same time, so you are calling the function is executed immediately.

The variable i is passed to the parameter j, and j in the IIFE will be printed after 3 seconds.

Changing var to let:

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

All you need to do is just changing the var to let.

How does this work? -> When you use var, i is in the scope of interviewQues(), so var can only hold one value at a time. If you use let, i is in the scope of for-loop, which means there are 5 scopes (depends on how many times you loop through), so you can print out 1, 2, 3, 4, 5 instead of printing 6 five times.

Did you find this article valuable?

Support Lim Woojae by becoming a sponsor. Any amount is appreciated!

ย