3

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;
pimvdb
  • 151,816
  • 78
  • 307
  • 352
CodeToad
  • 4,656
  • 6
  • 41
  • 53

4 Answers4

5

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).

ZER0
  • 24,846
  • 5
  • 51
  • 54
3

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.

Community
  • 1
  • 1
codebox
  • 19,927
  • 9
  • 63
  • 81
2

Try to keep one style the whole code through. It doesn't matter which one.

David 10K
  • 303
  • 2
  • 14
1

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.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636