Declaring a Javascript variable twice in same scope - Is it an issue?

前端 未结 3 764
甜味超标
甜味超标 2020-12-14 14:59

Would the following code cause any issues?:

var a = 1;
var a = 2;

My understanding is that javascript variables are declared at the start o

3条回答
  •  不思量自难忘°
    2020-12-14 15:31

    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
        // ...
    }
    

提交回复
热议问题