Facebook Pixel

What is the output of for (var i = 0; i < 3; i++) setTimeout(() => console.log(i), 0) in JavaScript?

3, 3, 3. var is function-scoped, so all callbacks share one i. By the time the callbacks run, the loop has finished and i is 3. Use let to fix this (each iteration gets a fresh binding).

Verify This Answer

Cross-check this information using these trusted sources:

More FAQs in Shadowing and Hoisting Interview Questions in JavaScript

Because the inner var x is hoisted to the top of the function with undefined, shadowing the outer immediately. A read before the assignment line sees undefined, not the outer value. This is the classic shadowing + hoisting trap.

Because the inner let is hoisted (shadowing the outer from the start of the block) and is in the TDZ. It does not fall back to the outer variable. Accessing it before the inner declaration line throws ReferenceError.

Because you cannot shadow a let with a var in the same scope. var ignores block boundaries and would leak out, creating two declarations of x in the same scope. The engine catches this at parse time.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Our courses are taking a Coffee break, but your curiosity shouldn't. Stay engaged with namastedev linkedin, youtube, discord and other resources while you wait.

0
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.
Please Login.