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 Repr...