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
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);
}