简体   繁体   中英

I'd just like to confirm… declaring (without assigning) variables that have already been declared does absolutely nothing, correct?

My tests suggest that the title is, indeed, correct. But I don't know if there is some subtle nuance that I'm not thinking of. See also: Is there anything wrong with declaring your vars inside of a for loop or an if block?

If they are in the same scope, your test is right. Redeclaring the same variable in the same scope does nothing.

But, if they are not in the same scope, re-declaring a variable in a local scope will create a new variable that will override the original within that scope.

So, this works fine:

var value = "foo";
var value;
console.log(value);   // "foo"

But, this creates a new variable in the local scope that does not have the value of the globally defined one:

var value = "foo";

function test() {
    var value;            // this creates a new variable that is separate
                          // from the globally declared one with the same name
    console.log(value);   // undefined
}

test();

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