In for...of, each iteration creates a fresh binding that does not change within the iteration, so const is fine. In a classic for loop, i++ reassigns i, which const does not allow, so it throws TypeError.
Block Scope and the Lexical Scope Chain
Why does const work in for...of but not in a classic for loop in JavaScript?
The answer
More FAQs in Block Scope and the Lexical Scope Chain
Yes. Every block with let or const declarations creates a new lexical environment. Its outer reference points to the enclosing environment, forming part of the scope chain.
No. var goes into the function's variable environment, not a block environment. This is why var leaks out of blocks but stays in the function. Only let and const use block environments.
Each block's environment has an outer reference to the enclosing environment. The engine checks the block first, then follows outer references up through function and global environments until the variable is found or ReferenceError is thrown.
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.