One var per function in JavaScript?

后端 未结 4 602
轮回少年
轮回少年 2020-12-04 10:37

I\'ve been using JSLint to make me feel bad about my JavaScript. It is great, by the way. There is one check that I don\'t quite understand and I\'d like your views, please.

4条回答
  •  旧时难觅i
    2020-12-04 11:39

    Yes, it means that you declare all variables at the beginning of the function. Whether you want to do it in one line or multiple lines is a matter of choice.

    The reason is explained in the paragraph you mentioned. Javascript variables only have function level scope. If you declare the same variable inside an if/while/for block, it will be overwritten by the new value since the block doesn't carry a new scope. This is different from languages such as Java. To avoid such surprises, declare all the variables you are going to use in the function at the beginning of function so that you don't accidentally 'redeclare' andything.

提交回复
热议问题