Home » JavaScript » Most Aksed Interview Javascript Question (Closure)

Most Aksed Interview Javascript Question (Closure)

Question aksed in Inteview : you have to write an Javscript code to print number in increasing order in each 1 secound differ or print num like at 1 sec- 1 , 2 sec -2 , 3 sec -3 … n sec -n.

srTime outOutput
111
222
333
444
555
666

Usually, the developer who answers this type of question often provides a solution quickly, which Looks correct but produces the wrong output.

Code :

Interview Javascript Question
Interview Javascript Question

Output Will Be Get is :

OutPut

Why it Happen ?

The reason behind the output we are getting is closure. I assume you know what closure is and how closures work. If you don’t, please read our blog on closure by searching on our platform Nileshblog.tech.

In Very short : Closure is a combination of lexical scope with a function. It means it contains a local function within the lexical parent function or scope.

in Javscript Closure is most important topic You Muct understand it first.

How The code is Executing ?

  1. For Loop:
    • Iterate from i = 1 to i = 5.
  2. Set Timeout Function inside Loop:
    • For each iteration, schedule a setTimeout function.
    • The function inside setTimeout logs the current value of i after a delay of i * 1000 milliseconds.
  3. Closure Concept:
    • Inner function has access to outer function’s variables, including i.
  4. Call Stack Execution:
    • NileshBlog is called.
    • setTimeout functions are scheduled but not executed immediately.
    • Loop completes and call stack is cleared.
  5. SetTimeout Delays:
    • First setTimeout has 1-second delay, second has 2 seconds, and so on.
  6. Execution of setTimeout Callbacks:
    • After delays, callback functions inside setTimeout are pushed into the call stack.
  7. Logging:
    • Callbacks log the value of i, referencing the same i through closure.
  8. Final Log:
    • “NileshBlog.Tech” is logged after loop completes and timeouts are scheduled.

Read : How to Convert Number to string in Javascript ?

Correct Approach to solve this problem ?

There are many approach to solve , we discuss here are two . first is just by simply replacing the let with constant.reason behind is this let create it seprate memory so that in every iteration it has uniques i copy.

1st appraoch :

Code:

function NileshBlog(){
for(let i=1;i<=5;i++){
        setTimeout(function(){
            console.log(i);
        },i*1000);
    }
    console.log("NileshBlog.Tech");

}

//output
Nileshblog.Tech
1
2
3
4
5

Execution of Appraoch :

  1. For Loop:
    • A for loop is used to iterate from 1 to 5.
  2. setTimeout Function:
    • Inside the loop, setTimeout is used to log the value of i after a delay.
    • The delay is set to i * 1000 milliseconds.
  3. Closure:
    • setTimeout is a function that takes a callback function as its first argument.
    • The callback function (function(){ console.log(i); }) forms a closure because it “closes over” the variable i.
  4. Execution of setTimeout:
    • setTimeout is asynchronous, so it doesn’t block the execution of the loop.
    • The loop continues to run, and each iteration schedules a new asynchronous task to log the value of i after a specific delay.
  5. Log “NileshBlog.Tech”:
    • After the loop, console.log(“NileshBlog.Tech”); is executed.
  6. Execution Result:
    • The numbers from 1 to 5 are logged after respective delays.

2 Approach : UsingFunction (Which create it seprate space /local executing context)

if you dont have knowledge about how the javascript is executed in backed you can read our blog on Javascript execution in backend or what is Execution context and excution context types ?.We understand that for every individual function, it creates its local execution context on top of the parent or global execution context. Therefore, in each iteration, it creates its own local space or space for its variables. Consequently, each setTimeout contains a separate and unique value of i for that iteration.

Code :

Technical interview
Coding interview
Interview preparation
Behavioral interview questions
Frontend development interview
Backend development interview
Node.js interview questions
Reactjs interview questions
JavaScript frameworks for interviews
Common JavaScript coding challenges
Problem-solving in interviews
Interview tips and tricks
Mock interviews for JavaScript
Interview success strategies
Job interview skills
Interview Javascript Question

Leave a Reply