🚨 JavaScript Question That Appears in Many Frontend Interviews What will be the output? for (var i = 0; i < 3; i++) { setTimeout(() => { console.log(i); }, 1000); } Many developers expect: 0 1 2 But the actual output is: 3 3 3 Why? Because var is function-scoped and all callbacks reference the same i. By the time setTimeout executes, the loop has already finished. Understanding closures and execution context makes questions like this much easier. JavaScript fundamentals still decide many frontend interviews. What other tricky JavaScript questions have you seen? #JavaScript #ReactJS #FrontendInterview #FrontendDeveloper #FrontendArchitecture #ProductBasedCompany
The simple reason is because javascript always stores the reference and not the actual value incase of var. After 3 setTimeouts functions the value of i in global scope or global memoery changes to 3. Hence it remembers the latest value because of reference and three times 3 is printed.
Good one👏 Here we have two ways to get the output as 0 1 2 1) simple use let instead of var 2)by manually creating a closure(creating the new lexical scope) function x(){ for(var i=0; i<3; i++){ function y(j){ setTimeout(function (){ console.log(j) },1000) } y(i); } } x();
Because var is function scope Loop chalne ke baad i ki final value 3 ho jati hai. setTimeout 1 second baad execute hota hai, tab tak loop finish ho chuka hota hai.
Keep sharing
A small change like replacing var with let completely changes the behavior here. Shows how important scope and closures are in JavaScript.