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

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

    I would venture to say that in older structures (such as the C\C++ days) it was important to initialize your variables and assign them a start value. But with the way things have been going, I'm finding that declaring them "when necessary" is a valid implementation. Unless scope is playing a part (for instance you need variable a not only in that function, but also in other functions, too), I would declare on-the-go.

    Maybe it's just way of thinking, but I tend to declare things based on scope (If the variable is needed only within an if condition or a few lines of code, I'll declare it there (rather than at the top of my function/class). If I don't go through that code path, I think of it as saving the memory allocation and it won't be declared for "no reason".)

    I could be completely wrong, however. Either way, JavaScript will allow you to declare your variables in any fashion you deem easiest to read.

提交回复
热议问题