Dealing with duplicate declaration warning for loop variables

前端 未结 5 1856
傲寒
傲寒 2021-02-02 05:44

Consider the following code:

for (var i=0; i<100; i++) {
    // your code here
}
// some other code here
for (var i=0; i<500; i++) {
    // custom code her         


        
5条回答
  •  迷失自我
    2021-02-02 06:29

    JavaScript has many constructions which look like well-known constructions in other computer languages. It's dangerous for JavaScript to interpret the construction in another way as most other computer languages.

    If somebody who doesn't know JavaScript good enough (the common case by the way) sees the construction like

    for (var i=0; i<100; i++) {
        // your code here
    }
    

    or sees declaration of the variable in the block

    {
        var i;
        //some code
        {
            var j;
            // some code
        }
    }
    

    then most readers will think that block level variables will be defined. JavaScript don't have block level variables. All variables will be interpreted as function level defined.

    So I never define variables inside of the code if the code is not just some test code which will be written for 5 min only. The main reason is that I don't want to write code and use language constructions which could be misunderstood.

    By the way JSLint finds defining of variables inside of block such bad style that it stop processing of the code analysis. There are no JSLint options which could change this behavior. I find the behavior of JSLint not good, but I agree that declaration of variables inside of for loop is bad because it will be read by most persons as code with local loop variables, which is incorrect.

    If you use

    for (var i=0; i<100; i++) {
        // your code here
    }
    // some other code here
    for (var i=0; i<500; i++) {
        // custom code here
    }
    

    then JavaScript moves all declarations of variables at the beginning of the function for you. So the code will be as

    var i = undefined, i = undefined; // duplicate declaration which will be reduced
                                      // to one var i = undefined;
    
    for (i=0; i<100; i++) {
        // your code here
    }
    // some other code here
    for (i=0; i<500; i++) {
        // custom code here
    }
    

    So please think about other readers of the code. Don't use any constructions which could be interpreted in the wrong way.

提交回复
热议问题