0

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

Alexander Mills
  • 90,741
  • 139
  • 482
  • 817
  • 2
    Well `i` would be global so yes it is best practice to declare it – epascarello Nov 03 '17 at 18:43
  • In `strict` mode, using a variable without declaring it is an error and, for very good reason, because creating an accidental or implicit global is very easy to make a messy, hard to find bug, particular when there is async code involved. So, NEVER use a variable without declaring it. To be safe, put all your code in `strict` mode. Some ES6 things are automatically strict mode such as methods on a class declaration. – jfriend00 Nov 03 '17 at 18:47

1 Answers1

5

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.

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
  • @BhojendraNepal See https://stackoverflow.com/questions/44606868/difference-between-let-and-var-inside-settimeout – str Nov 03 '17 at 18:48
  • @BhojendraNepal - There are hundreds of articles on `let` vs. `var`. Please read ten of them and then file your own question is there's still something you don't understand. We are way more effective if you use us for things that can't easily be found on Google. – jfriend00 Nov 03 '17 at 18:48
  • You should mention `strict` mode and mention ES6 code that is automatically in `strict` mode where it IS required to declare it first. – jfriend00 Nov 03 '17 at 18:49