Is it bad practice to use the same variable name in multiple for-loops?

Since variable declarations are hoisted to the top of the scope in which they appear the interpreter will effectively interpret both versions in the same way. For that reason, JSHint and JSLint suggest moving the declarations out of the loop initialiser.

The following code...

for (var i = 0; i < 10; i++) {}
for (var i = 5; i < 15; i++) {}

... is effectively interpreted as this:

var i;
for (i = 0; i < 10; i++) {}
for (i = 5; i < 15; i++) {}

Notice that there is really only one declaration of i, and multiple assignments to it - you can't really "redeclare" a variable in the same scope.

To actually answer your question...

is there a best practice for this or could I just go with any of the codes above?

There are varying opinions on how best to handle this. Personally, I agree with JSLint and think the code is clearer when you declare all variables together at the top of each scope. Since that's how the code will be interpreted, why not write code that looks as it behaves?

But, as you've observed, the code will work regardless of the approach taken so it's a style/convention choice, and you can use whichever form you feel most comfortable with.


It has been mentioned only in the comment by @TSCrowder: If your environment supports it (Firefox, Node.js), in ES6 you can use let declaration

//for-loop 1
for (let i = 0; ...; i++) { ... }

//for-loop 2
for (let i = 0; ...; i++) { ... }

which limits the scope to within the for-loop. Bonus: JSHint stops complaining.