简体   繁体   中英

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?

As you see, the first value appears twice and all other values to the max number appears only one time.

So it makes no sense at all, to use this pattern.

The redeclaring is moved to top and used only once for the same variable.

 for (var i = 0; i < 10; ++i){ console.log('outer', i); for (var i = 0; i < 20; ++i){ console.log('inner', i); } } 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM