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

前端 未结 6 1535
滥情空心
滥情空心 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 09:43

    This is really just a matter of preference. For example, if my method only contains a for loop, then I won't extract the loop variables to the top:

    var func = function(arr) {
        for (var i = 0, len = arr.length; i < len; i++) {
            // array processing here
        }
    }
    

    Almost all other times though I will place ALL variables at the top for hoisting reasons. If you find that there are too many variables at the top of your function, it could be an indication that your method is doing too much work, and should consider extracting a portion of it into some sort of helper method. This will let you organize your variables based on functionality.

提交回复
热议问题