Search code examples
javascriptfor-loopconstantslet

Why can a for..of / for..in loop use const while a normal for loop can only use let or var for its variable in JS?


In JavaScript, you can do something like this:

const arr = [1, 2, 3, 4, 5];

for (const v of arr) console.log(v);

But in normal for loop, it gives a TypeError:

for (const i = 0; i < 5; i++) console.log(i);

// TypeError: Assignment to constant variable.

Shouldn't the for..of get an error as well?


Solution

  • No the for(...of...) loop won't get an error. Here is why:

    In the second for loop, you are editing the constant variable which is NOT allowed. This throws a TypeError. In the first for loop, it doesn't matter what type of variable assignment you use. The variable (const,let, var, or no identifier) calls on the iterator which creates a sort of isolated temporary scope. This is why you can't access the variable outside of the for loop. For example:

    const example = 1;
    example = 2;
    //TypeError
    
    for (const someVar of Array(5)) someVar = 12;
    //TypeError
    
    {
        const num = 200;
    }
    
    const num = 150;
    //This is fine because of scope