Alexander Mills
Alexander Mills

Reputation: 99980

Do we need variable declaration using `for..of` / `for..in` loops

I see examples like this online:

const roles = [];

for (i of roles) {
  roleObj[roles[i].key] = true;
}

do we need not declare the variable i, like so?

for (let i of roles) {
  roleObj[roles[i].key] = true;
}

tons of articles are promoting the first example, which seems pretty dumb to me:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

Upvotes: 0

Views: 97

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

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.

Upvotes: 5

Related Questions