4

In javascript variables have function scope only. So it's either global or it's a variable accessible in the entire function regardless of exactly where it was declared (within the function).

I'm guessing best practice would be to declare all variables at the top level right after 'use strict'; ?

What happens if I have 5 loops where I declare the same i var?

for (var i = 0; i < someValue; i+=1) { ... } 

Is the variable simply reset to 0 or whatever the loop sets it's initial value and everything moves on ? Can this cause complications ?

Kalec
  • 2,681
  • 9
  • 30
  • 49
  • 1
    The variable declaration is hoisted to the top, so declaring `var = 0` right at the top would do fine, then on every loop `i = 0` is just reinitialising the variable on that line, so that won't cause complications, whether that is good practice or not is another question. – Mark Walters Sep 04 '15 at 11:52
  • 1
    I would recommend playing around on the console and test it for yourself. – João Gonçalves Sep 04 '15 at 11:53
  • 1
    @JoãoGonçalves Everything I've heard of JS so far tells me it tends to do a lot of subtle stuff that is not always imminently noticeable. I'm afraid of forming bad habits is JS more than any other language I've seen. – Kalec Sep 04 '15 at 12:04

1 Answers1

2

As you can see, i is set to 0 at the start of the for loop: i = 0. The var i part is hoisted to the top of the function and every additional var i … redeclares i, and the i = 0 part redefines it. Redeclaration is unnecessary and makes the code less clean (JSHint warns you about this).

If you use i later, outside of any loop, that i is set to whatever the for loop did with it.

for(var i = 0; i < 4; i++){
  /*
  As the last few steps i is incremented (i == 4),
  then it is checked with (i < 4), which is false; the loop is done.
  */
  //…
}
i; // 4

Because you’d normally redefine every iteration variable in the head of the loop, this cannot cause any other problems.

However, for cleaner code it’s wise to use one variable per loop, or to make let variables, instead of var variables, as let variables are scoped to the for loop block only:

for(let i = 0; i < 20; i++){
  // …
}

for(let i = 0; i < 10; i++){ // This is fine.
  // …
}

let variables are only available in ECMAScript-6-compliant browsers and in Firefox require a version opt-in.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75