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?
If you are minifying your javascript, there is a fairly large benefit:
becomes
Where as
becomes
That's an additional three instances of
var
, which can add up over time.See The "A List Apart" article series "Better Javascript Minification" Part 1 and Part 2
After reading Crockford and others, I started to chain my variables with comma exclusively. Then later, I really got annoyed by the Chrome DevTools debugger that wouldn't stop at variable definitions with comma. For the debugger, variable definitions chained with comma are a single statement, while multiple var statements are multiple statements at which the debugger can stop. Therefore, I switched back from:
To:
By now, I find the second variant much cleaner, not to mention its advantage of solving the debugger issue.
The "less code through the wire" argument is not persuasive, as there are minifiers.
The first saves a few characters--so there is a very small saving in terms of the JS filesize and therefore bandwidth consumption. The only time this would become noticable would be in extreme cases.
I prefer the second version (each has its own
var
). I think that's because I come from a C++ background. In C++, you can declare variables like you do in your first example, but it is frowned upon (it easily leads to mistakes when you're trying to create pointers that way).As others have noted, it is a style preference. JSLint might tell you to only have one
var
per function (if you use the "Good Parts"). Thus if using JSLint to check your code (not a bad idea, IMHO), you'll end up using the first format more than the latter.On the other hand, the same author, Douglas Crockford, says to put each variable in its own line in his coding conventions. So you may want to uncheck the "All one
var
per function" checkbox in JSLint if you use it. ;-)Since I don't see any references to it, here is a link to the ECMA-262 specification, which is the underlying spec for JavaScript. The grammar from that page says:
What you can glean from this is using commas or not doesn't matter. Either way, it ends up being parsed as a
VariableDeclaration
and is treated exactly the same. There should be no difference to how the script engine treats the two declarations. The only differences would be ones already mentioned in other answers - saving more space and practically immeasurable differences in the amount of time it takes to apply the grammar to find all theVariableDeclarations
when the script is compiled.