Is there any purpose to redeclaring JavaScript variables?

前端 未结 9 1773
傲寒
傲寒 2020-12-11 18:38

I am new to JavaScript.





        
9条回答
  •  执笔经年
    2020-12-11 19:15

    var alone does not perform an assignment. It only flags that when you use the variable name throughout the scope in which the var occurs, you are talking about a local variable and not global (the controversial default). The var is spotted when the function is parsed and holds throughout that scope, so where you put it is irrelevant:

    var a= 0;
    
    function foo() {
        a= 1;
        return a;
        var a;
    }
    
    var b= foo();
    alert('global a='+a+', local a='+b);
    

    Results in global a= 0, local a= 1: even though the var statement is never reached in the course of execution of foo(), it is still effective in making a a local variable.

    So declaring var x a second time in the same scope is completely redundant. However you might sometimes still do it, typically when you re-use a local variable name for a second independent use within the same function. Most commonly:

    for (var i= 0; i

    Whilst you could certainly omit the second var, and tools like jslint would demand you do so, it might not actually be a good idea.

    Imagine you later change or remove the first loop so that it no longer declares i to be var. Now the remaining second loop suddenly changes meaning from a local to a global variable. If you fail to notice when updating the first loop that the second loop has a hidden dependency on it (and you might very well fail to notice that given how the eyes elide the pattern for(...=0 ; ...<...; ...++) into “oh, that's just a standard iterator”), you've got a subtle and annoying-to-debug problem.

提交回复
热议问题