Javascript Interview Questiosn
Here's a LinkedIn post that teaches the concept in a way that's easy to understand and encourages engagement.
π€ JavaScript Interview Question: var vs let with setTimeout
Can you guess the output before running the code? π
for (var i = 0; i < 3; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}
for (let j = 0; j < 3; j++) {
setTimeout(function () {
console.log(j);
}, 1000);
}
❓What will be printed after 1 second?
Option A
0
1
2
0
1
2
Option B
3
3
3
0
1
2
Option C
0
0
0
3
3
3
π Comment your answer before reading the explanation!
✅ Correct Answer: Option B
3
3
3
0
1
2
Why does var print 3 3 3?
for (var i = 0; i < 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
var is function-scoped, not block-scoped.
There is only one variable i shared across all iterations.
By the time setTimeout() executes (after 1 second), the loop has already finished.
i = 3
So every callback prints:
3
3
3
Visual Representation
Loop Starts
Iteration 1 ─┐
Iteration 2 ─┼──► Same variable: i
Iteration 3 ─┘
Loop Ends
i = 3
After 1 second
Callback 1 → 3
Callback 2 → 3
Callback 3 → 3
Why does let print 0 1 2?
for (let j = 0; j < 3; j++) {
setTimeout(() => {
console.log(j);
}, 1000);
}
let is block-scoped.
JavaScript creates a new copy of j for every iteration.
Iteration 1 → j = 0
Iteration 2 → j = 1
Iteration 3 → j = 2
When the callbacks execute later, each one remembers its own value.
0
1
2
Visual Representation
Iteration 1 → j = 0
↓
Callback remembers 0
Iteration 2 → j = 1
↓
Callback remembers 1
Iteration 3 → j = 2
↓
Callback remembers 2
After 1 second
0
1
2
π‘ Interview Follow-up Question
How can you make var print 0 1 2?
Answer:
for (var i = 0; i < 3; i++) {
((x) => {
setTimeout(() => {
console.log(x);
}, 1000);
})(i);
}
or simply use let, which is the modern and recommended approach.
π― Key Takeaways
✅ var → Function Scope
✅ let → Block Scope
✅ setTimeout() is asynchronous and executes after the loop completes.
✅ Closures capture variables differently depending on how they're declared.
π Save this post if you're preparing for JavaScript, Angular, React, or Node.js interviews.
π¬ Bonus Interview Question:
Can you explain what a Closure is and why it affects this example?
Follow AndroidMani for more JavaScript interview questions, Angular tips, and Full Stack development content.
#JavaScript #TypeScript #Angular #React #NodeJS #Frontend #WebDevelopment #CodingInterview #JavaScriptDeveloper #Closures #AsyncJavaScript #SetTimeout #Programming #SoftwareEngineer #FullStackDeveloper #AndroidMani
Comments
Post a Comment