When declaring variables at the top of a function, is there a difference between those two ways to do so?
var firstvar;
var secondvar;
var thirdvar;
and
var firstvar,
secondvar,
thirdvar;
When declaring variables at the top of a function, is there a difference between those two ways to do so?
var firstvar;
var secondvar;
var thirdvar;
and
var firstvar,
secondvar,
thirdvar;
Here there is a very well written blog post about multiple var statements vs single ones. I have to say that I mostly agree with Ben Alman: when I started with JS years ago, I used single statement but I switched to multiple statement for maintenance and readability reasons. Of course, I'm still using single var statement where it makes sense (e.g. when I don't have to assign values to those variables and where they are all logically related).
The commonly used static code analysis tool JSLint would tell you to combine them all into a single var statement. There is a fair explanation of why this is a good idea in the answer to this question.
It's purely a matter of personal preference. Most people seem to use the var x, y, z
way (with one variable per line) though.
JSLint also suggests to use only one var
statement, but the rules of that tool were obviously influenced by its developer's preferences, too.
However, I've seen quite a few auto-indent tools (for example, every single one that is available for Vim) to break in some cases when using multi-variable var
statements so if that's the case for you, too, you better use separate var
statements.