2

I often uses the "for of" statement to traversal an iterator, just like the following:

for(item of myIterator){
    console.log(item)
}

But recently, I found that the offical statement is:

for(let item of myIterator){
    console.log(item)
}

And they are both executing right, I wonder if they have any difference. Thx!

mq l
  • 21
  • 1
  • The difference is that `item` is unknown to JavaScript unless you declare it first, so the first example creates a linter warning. –  Mar 01 '20 at 16:47
  • 1
    Does this answer your question? [Is using 'var' to declare variables optional?](https://stackoverflow.com/questions/2485423/is-using-var-to-declare-variables-optional) – Marko Gresak Mar 01 '20 at 16:49
  • Without `let`, `item` becomes a global variable (assuming you haven't declared it with `let` or `var` before the for loop) – slebetman Mar 01 '20 at 16:55

3 Answers3

2

Let is a scoped variable, so will only work inside it's scope {}.

var myIterator = [0,1,2,3]

//non scoped variables works also out of for-loop, check
for(item of myIterator){
    console.log(item)
}

console.log(item)

The above example will print all items and when finished, item variable is still the last item of the iteration Now try again with let scoped variable

//scoped variables works only inside for-loop instruction
for(let item2 of myIterator){
    console.log(item2)
}

console.log(item2)

Now item2 is no longer avaliable, because is out of scope and the instruction with throw an error.

danielarend
  • 1,379
  • 13
  • 26
0

When you use a variable that is not already declared, javascript will declare it in the current function scope or in the global object scope (aka window in browser, or global in node.js), this is the same behavior when you use the var keyword to declare a variable.

So your first "for of" will create a variable named item that is accessible outside of for scope.

The let keyword has block scope, so it's accessible only inside the for loop.

const arr = [1, 2, 3]

for (item of arr) {
    console.log(item)
}

for (let item2 of arr) {
    console.log(item)
}

console.log(item)
console.log(item2)

The second console.log will fail with a ReferenceError: item2 is not defined.

secato
  • 1
  • 2
  • It explains the matter, I really didn't know that a variable can be assigned before declared in JavaScript althrough I have wrote it for two years – mq l Mar 06 '20 at 07:27
0

Using let in this way will let you avoid accidentally creating a closure if you are calling a function in your loop and passing the counter as a parameter.