How do var, let and const differ?
Short interview answer
var is function-scoped and can be redeclared. let and const are block-scoped and cannot be used before their declaration. const prevents reassignment of the binding, but an object held by const can still be mutated.
Code example
for (var i = 0; i < 3; i += 1) {
setTimeout(() => console.log(i), 0);
}Expected output
3
3
3Why it happens
All callbacks close over the same function-scoped i. By the time they run, the loop has finished and i is 3. Replacing var with let creates a new binding for each iteration, producing 0, 1, 2.
What the interviewer is testing
Block scope, closure timing and whether you can predict a common loop bug.