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

后端 未结 4 802
被撕碎了的回忆
被撕碎了的回忆 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:30

    Declaring variables at the top helps you avoid situations like this:

    function outer() {
      var i = 50;
    
      function inner() {
        alert(i);
        var i= 30;
      }
      inner();
    }
    
    outer();
    

    Many people would expect the alert to show 50, and they would be surprised to see undefined. That's because the i variable is declared within the inner function, but it isn't initialized until after the alert. So it has full function scope, even though it's declared after its initial use.

提交回复
热议问题