The benefits of declaring variables at the top of the function body in JavaScript

后端 未结 4 867
被撕碎了的回忆
被撕碎了的回忆 2021-02-04 17:43

I am reading Douglas Crockford\'s book \"Javascript: The Good Parts\". He is talking about scope and saying that JS doesn\'t have block scope:

In many mod

4条回答
  •  忘掉有多难
    2021-02-04 18:31

    Declare variables at the top of the function as a means of documenting all variables used in one place.

    It also avoids confusion resulting from someone imagining that a variable is block-scoped when it is in fact not, as in the following:

    var i=0;
    if (true) {
       var i=1;
    }
    // what is i? C programmer might imagine it's 0.
    

    If variables are also being initialized at declaration time, putting the declarations at the top avoids potential problems with the timing of the initialization:

    console.log(foo);
    var foo = 1;
    

    In this case, foo is hoisted so it is declared at the time of the console.log, but has not yet been initialized. So this is effectively like

    var foo;
    console.log(foo); // no ReferenceError, but undefined
    foo = 1;
    

提交回复
热议问题