4

Having this two options:

Option A:

var index;
for (index in myObject) {
  // Do something
}

Option B:

for (var index in myObject) {
  // Do something
}

I don't know if in the option B the variable index it's being redeclared every time of the loop or just once.

Enzo
  • 4,111
  • 4
  • 21
  • 33

2 Answers2

4

Those two snippets of code do exactly the same thing (and that's the case in most language such as C, C++ and C# amongst others). If the variable was redeclared at every iteration, then following your logic, it would also be re-initialized, and would constantly loop over the same object. Your loop would be infinite.

On a side-note, in JavaScript, all variable declarations get pushed to the function scope; this means that you can declare variables anywhere within a function, even within nested loops, and they will only be declared once.

Link to the var documentation

Relevant SO question

Other relevant SO answer

Edit courtesy of @torazaburo:

If you want to declare a variable with a local scope (as in, a variable that will only be defined in the current block such as a for, while or if, you can use the let statement:

let var1 = 123;

It also allows you to override variables with the same name but declared in a higher scope, such as in this example from the docs:

function letTest() {
    let x = 1;
    if (true) {
        let x = 2;  // different variable
        console.log(x);  // 2
    }
    console.log(x);  // 1
}

See the full documentation (and examples) here.

Community
  • 1
  • 1
pie3636
  • 795
  • 17
  • 31
  • It would seem highly useful to include in this answer how `let` works in this context. –  Jul 31 '16 at 09:38
2

The preferred approach in 2016 is to declare the variable in the loop head, using let:

for (let i = 0; i < max; i++) { }
     ^^^

There is probably minimal performance difference between this and other approaches, but there are major advantages in terms of the robustness and clarity of your code.

First, with let, i is local to the for construct, so it can't "leak out", or modify some other i in an outer scope.

Second, and perhaps more importantly, a new version of i is created for each iteration of the loop. In technical terms, "you get a fresh binding for each iteration if you let-declare a variable" (see this excellent article). This solves the age-old problem of closures created inside the for-loop using the final value of i. We can now just write

for (let i = 0; i < 10; i++) {
  setTimeout(() => alert(i), i * 1000);
}

instead of having to do some clumsy work-around such as

for (var i = 0; i < 10; i++) {
  (function(i) {
    setTimeout(() => alert(i), i * 1000);
  }(i));
}

which has been the topic of countless questions here on SO, and which many of you have wasted far too many brain cycles learning.