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

前端 未结 6 1533
滥情空心
滥情空心 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:40

    In languages with block scope, it is usually recommended that variables be declared at the site of first use.

    But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. This way you don't fool yourself or other people about the variable's scope.

    EDIT: Many people work with several languages simultaneously. Often JavaScript is the only one among them without the block scope.

提交回复
热议问题