Can I declare the same variable twice in different for loops in JavaScript?
No you shouldn't. Variables declared using var
have function scope, not block scope!
Redeclaring a variable using var
might suggest that the variable is local to the loop/block when it isn't.
You could, however use let
to declare the variable, to ensure it is block-scoped.
for (let x = 1; x <= 3; x++) {
console.log(x)
}
for (let w = 65, x = String.fromCharCode(w); w <= 67; w++, x = String.fromCharCode(w)){
console.log(x)
}
console.log(typeof x) // undefined
Any use of var foo
in a function will scope foo
to that function. It doesn't matter where in the function this takes place as var
declarations are hoisted.
Additional uses of var foo
in the same function are syntactically legal but will have no effect as the variable is already scoped to that function.
Since it has no effect, there is a school of thought that recommends against it (and in favour of a single var
function at the very top of a function to perform all the scoping) to avoid implying that there is significance to it (to maintainers who are not entirely comfortable with this feature of JavaScript). JSLint will alert you to this usage.