What are the differences and/or advantages, if any, of using commas when declaring a group of variables rather than semicolons.
For example:
var foo = 'bar', bar = 'foo';
versus
var foo = 'bar';
var bar = 'foo';
I know that if you specify the var
keyword on the first variable in the first example it persists across all of the variables, so they both produce the same end result regarding scope. Is it just personal preference, or is there a performance benefit to doing it either way?
No performance benefit, just a matter of personal choice and style.
The first version is just more succinct.
Update:
In terms of the amount of data going over the wire, of course less is better, however you would need a hell of a lot of removed
var
declarations in order to see a real impact.Minification has been mentioned as something that the first example will help with for better minification, however, as Daniel Vassallo points out in the comments, a good minifier will automatically do that for you anyways, so in that respect no impact whatsoever.
I prefer the
var-per-variable
notation:because the other
comma-instead-of-another-var
notation have these three shortcomings:1. Hard to maintain
Consider this code:
But hey, what does the mogrify do? Let's print b to find out:
breaks stuff
2. Hard to read
The var in the begging of the line clearly communicates that there will be a new variable initiated.
What the hell is the
c = 3
doing there right?3. Not consistent
Consider this:
With
var-per-variable
every declaration follow the same structure. Withcomma-instead-of-another-var
the first variable is declared in different way than others. If you decide to, say, move the first variable inside a for cycle, you will have to add var to the middle of declarationsOther than preference, it seems like majority of notable projects use the
var-per-variable
notationI agree with the other answerers that this is mainly a matter of personal style. But to bring an "Authoritative" opinion into the discussion, this is what Douglas Crockford says on the website of the popular JSLint tool:
I don't think there's any noticeable difference, as far as I'm concerned it's just personal preference.
I hate having multiple var declarations so I usually do:
As it's shorter and arguably more readable, no
var
noise to look at.