Search code examples
javascriptloopsconstantsletfor-of-loop

Is there no difference between let and const inside for of loop in Javascript in terms of declaration?


I recently came across this code:

for (const temp of [1,2]) {
  // do something
}

I thought that it'd be better to use let declaration for temp because this way the variable would be declared only once. However, I also ran this example as well as the version with let through babel and this is what I see:

for (const p of [1,2]) {

}

for (let s of [1,2]) {

}

became:

for (var _i = 0, _arr = [1, 2]; _i < _arr.length; _i++) {
  var p = _arr[_i];
}

for (var _i2 = 0, _arr2 = [1, 2]; _i2 < _arr2.length; _i2++) {
  var s = _arr2[_i2];
}

So babel treats const and let identically. I'm wondering if Javascript runtime treats the 2 versions identically under the hood. Is the conclusion of this is that even if a variable is declared with let inside the loop it will still be redeclared on each iteration?


Solution

  • I thought that it'd be better to use let declaration for temp because this way the variable would be declared only once.

    There's a new version declared for each loop iteration either way; this is important for addressing the closures-in-loops problem:

    const array = [1, 2, 3, 4];
    for (const entry of array) {
        setTimeout(() => {
            console.log(entry);
        }, 0);
    }

    If there weren't a new variable created for each loop iteration, that would log the same value (probably 4) four times.

    Choosing let or const is down to:

    1. Do you want to be able to assign it a new value within the loop?

    2. Your personal style preference (or your team's preference).

    I'm wondering if Javascript runtime treats the 2 versions identically under the hood.

    Yes, other than that you can assign the let variable a new value within the loop if you like.¹ For instance:

    const strings = ["a", "b", "c"];
    for (let str of strings) {
        str = str.toUpperCase();
        console.log(str);
    }

    E.g., the only difference is whether the variable is mutable or not.


    ¹ For the avoidance of doubt: All that assigning to it does is change that variable's value. It has no effect on the array/iterable that the value came from.