Search code examples
javascriptfor-of-loop

why do we use const in for...of loops in javascript?


I am wondering why we use const in javascript for...of loops. Every example I see using for...of loops use const while declaring the variable. For example:

for (const item of array) {
    // do something
}

Is there any reason we don't use var like this?

for (var item of array) {
    // do something
}

Thanks


Solution

  • var will load the variable into the global scope, whereas let and const will declare it in the lexical scope:

    const test = [1, 2, 3];
    
    // lexical
    for (let testItem of test) {
        console.log(window.testItem);
    }
    
    // global
    for (var testItem of test) {
        console.log(window.testItem);
    }