Declaring a Javascript variable twice in same scop

2020-02-08 23:58发布

问题:

Would the following code cause any issues?:

var a = 1;
var a = 2;

My understanding is that javascript variables are declared at the start of the scope. For example:

var foo = 'a';
foo = 'b';
var bar = 'c';

Is processed as:

var foo;
var bar;
foo = 'a';
foo = 'b';
bar = 'c';

Therefore would my initial code snippet become:

var a;
a = 1;
a = 2;

Or would it become:

var a;
var a;
a = 1;
a = 2;

I understand that declaring a javascript variable twice in the same scope isn't good practice, but I'm more interested in the impact of doing this.

回答1:

As you said, by twice of more the same var, JavaScript moves that declaration to the top of the scope and then your code would become like this:

var a;
a = 1;
a = 2;

Therefore, it doesn't give us any error.

This same behaviour occurs to for loops (they doesn't have a local scope in their headers), so the code below is really common:

for (var i = 0; i < n; i++) {
    // ...
}
for (var i = 0; i < m; i++) {
    // ...
}

That's why JavaScript gurus like Douglas Crockford suggest programmers to manually move those declarations to the top of the scope:

var i;    // declare here
for (i = 0; i < n; i++) {    // initialize here...
    // ...
}
for (i = 0; i < m; i++) {    // ... and here
    // ...
}


回答2:

Declaring the same variable twice is as good as declaring it once. Below statement will not bring any impact.

var a, a;

in the below case you are just overriding the variable foo. This will have an impact if you have foo defined in the local and global scope. JS will search foo in the local scope first and then if it doesn't find it will look in the global scope.

var foo;
var bar;
foo = 'a';
foo = 'b';
bar = 'c';


回答3:

Such a duplicate variable declaration will not cause any problems thanks to javascript's variable hoisting feature. so in your DOM wherever you have declared variables but assigned (or) not assigned, they will be placed at the top during compilation.

Example:
    var foo='hai!';
    bar='welcome!';
    var bar;

You may expect above code snippet should throw "unidentified" error but still javascript manages it by placing the bar variable's declaration at the top. So even before variable declaration its value can be assigned as opposed to other languages.

Hope this helps you to some extent