Is defining every variable at the top always the best approach?

前端 未结 6 1555
滥情空心
滥情空心 2021-02-02 09:02

I\'ve heard that it is a good technique to define your variables at the top of a function, so you don\'t end up with variable hoisting problems. This:

// Beginni         


        
6条回答
  •  长情又很酷
    2021-02-02 10:04

    This is a style question. Not a functionality question.

    The javascript parser will take this code

    function() {
       dostuff();
       var i = 4;
    }
    

    and turn it into :

    function() {
       var i;
       dostuff();
       i = 4;
    }
    

    As for the style question. No thank you I thought we left that behind with ANSI C.

    What you want to do is declare functions at the top of their "scope"

    If the "scope" of a variable is the entire function then declare them at the top. If the "scope" is a subset of a function then declare them at the start of the subset.

    treat "scope" as logical scope rather then function scope.

    This should ensure maximum readability.

提交回复
热议问题