Facebook Pixel
Hoisting in Loops and Conditionals in JavaScript

Why does let in a for loop log different values in setTimeout callbacks?

The answer

Because let is block-scoped and the spec gives each iteration a fresh binding. Each closure captures its own copy of i, so callbacks log 0, 1, 2 instead of the final value.

More FAQs in Hoisting in Loops and Conditionals in JavaScript

Because var is function-scoped. There is one i shared by all iterations. By the time the setTimeout callbacks run, the loop has finished and i equals the final value, so all callbacks log that value.

Yes. var ignores block boundaries (except function bodies), so a var inside an if is hoisted to the enclosing function or global scope. let and const are block-scoped and do not leak.

Use let instead of var (each iteration gets a fresh binding), or wrap the body in an IIFE that captures the current value of i as a parameter.

Still have questions?

Browse all our FAQs or reach out to our support team

Want to upskill yourself?

Your learning library

Small steps. Big possibilities.

Find your next course. Build something great.

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.
Please Login.
Please Login.
Please Login.