You don't absolutely need to, but it's highly recommended to do so and in fact to use let
. Note that using let i
in this case will actually function differently than if you just did for (i
or for (var i
.
As an example:
for (let i = 0; i < 10; i++) {
process.nextTick(() => console.log(i));
}
// print 0..9
for (var i = 0; i < 10; i++) {
process.nextTick(() => console.log(i));
}
// prints 10 ten times.
Also note that with let
you would not be able to use i
after the loop, but you could with var
, and if you do not use var
the variable will be in the global scope so it would work differently if it were inside of a function:
function gl() {
for (i = 0; i < 10; i++) {}
for (var j = 0; i < 10; i++) {}
for (let x = 0; i < 10; i++) {}
console.log(i, j) // prints 10, 10
console.log(x) // runtime error
}
gl();
console.log(i) // prints 10
console.log(j) // runtime error
Also, as mentioned in the comments, accessing variables without declarations is not allowed in strict mode.