Search code examples
javascriptscopevariable-declarationredeclaration

Re-declaring variables in Javascript


I found out today (via the hard way) that JavaScript allows this to be done, without generating any errors:

for(var i = 0; i < 100; ++i){
    /* do some stuff */
    for(var i = 0; i < 200; ++i){
        /* do some more stuff */
    }
}

I used the same identifier i for both loops by accident.

The JavaScript compiler/interpreter does not produce an error (like Java), and neither does it create a different variable that hides the variable on the outer loop (like C++). They refer to the same variable, so the outer loop will only be run once!

Why is this so? Is this behaviour useful in any circumstance at all?


Solution

  • I can't find any use for this. The ability to do var i; twice without any warnings or errors seems to be an imperfection with the language.

    As pointed out in this comment, the usage of let instead of var solves this problem. While var is hoisted up to the start of the function body, let is only hoisted up to the closest {. let isn't supported widely yet, though, so it shouldn't be used just yet if you need to maintain compatibility with older browsers.

    Code checking tools like JSHint can help to detect such duplicate declaration problems.