94

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?

STW
  • 44,917
  • 17
  • 105
  • 161
Collin Klopfenstein
  • 2,265
  • 4
  • 21
  • 22

10 Answers10

73

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.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • 8
    There is a performance benefit when minifying your javascript. – Ryan Kinal Sep 23 '10 at 18:53
  • 1
    @Ryan Kinal - where exactly in the question do you see minifying mentioned? – Oded Sep 23 '10 at 18:54
  • 2
    @Oded -- minification is in-line with performance concerns. Therefore, if one style lends itself to better minification, then it lends itself indirectly to performance concerns – STW Sep 23 '10 at 19:03
  • I guess if you're declaring a lot of variables in different scopes you're saving yourself, what, 4 bytes per variable? That adds up. – Collin Klopfenstein Sep 23 '10 at 19:04
  • 7
    @Ryan: Good minifiers, like the Google Closure Compiler will merge multiple var statements into one: http://img840.imageshack.us/img840/3601/closurecompilerservice.jpg – Daniel Vassallo Sep 23 '10 at 19:04
  • So I looked at Closure Compiler and it looks cool...but on anything higher than Whitespace Only, it does some obfuscation that scares me. Like if I write a jQuery plugin and wrap it with `( function ( $ ) { ... } )( jQuery )` it converts all the `$` to `a`, just to name one. On the aggressive setting, it completely broke the plugin that I tested by changing `$.myPlugin` to `$.m`. To be fair though, its whitespace only mode is still a LITTLE more effective than http://minifyjs.com. – Collin Klopfenstein Sep 23 '10 at 19:36
  • @Oded The question is about advantages and disadvantages of the two techniques. Minification is something to take into account in that discussion, I believe. – Ryan Kinal Sep 23 '10 at 21:57
  • There is an often overlooked advantage to declaring var only once and separating the different vars with commas. In JS, all variables and functions are hoisted to the top of the function in scope, so there is a performance advantage of having all the vars at the top, sparing the JS engine from having to do it for you. If you only use one var declaration per function, it's easier to keep track of all your vars and prevent any of them from getting hoisted, so it's a good habit to develop. – Derek Henderson Jun 20 '13 at 09:15
  • @DerekHenderson - It that even measurable? I'd expect such an optimization to be near impossible to measure. – Oded Jun 20 '13 at 09:16
  • I don't know, never tried measuring it. I'm going by Crockford's dictate about declaring vars at the top to avoid hoisting, and I find it easier to keep track of this when there's only one `var` declaration. – Derek Henderson Jun 20 '13 at 09:18
  • @DerekHenderson - I see that as more of a code readability recommendation than performance. – Oded Jun 20 '13 at 09:23
  • 2
    Yes, you are right. Out of curiosity, I created a test (http://jsperf.com/var-declarations-multiple-vs-single-and-top-vs-all-over), ran it 5 times, and got 5 different answers. So, um, yeah, it's all about style and personal preference, not performance. – Derek Henderson Jun 20 '13 at 09:51
30

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:

var a = doSomethingA,
    b = doSomethignB,
    c = doSomethingC;

To:

var a = doSomethingA;
var b = doSomethignB;
var c = doSomethingC;

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.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Felix
  • 769
  • 1
  • 7
  • 8
  • 1
    I have actually experienced this myself. I typically just split the declaration where I need to check something, and drop a `debugger` in there, then add another `var` and keep comma-chaining them. Then when I'm done debugging I go back and remove the `debugger` and extra `var`. – Collin Klopfenstein May 22 '14 at 18:26
  • 8
    The second variant also makes git history cleaner. Instead of having to change the trailing semicolon into a comma before adding another variable or risk creating a global variable you simply add a complete var statement. – payne8 May 20 '16 at 18:20
  • to mention, first form can errorneously make you think b or c is global. – garg10may Nov 09 '17 at 13:38
18

I prefer the var-per-variable notation:

var a = 2
var b = 3

because the other comma-instead-of-another-var notation have these three shortcomings:

1. Hard to maintain
Consider this code:

var a = 1,
    b = mogrify(2),
    c = 3

But hey, what does the mogrify do? Let's print b to find out:

var a = 1,
    b = mogrify(2),
    console.log(b)
    c = 3

breaks stuff

2. Hard to read

The var in the begging of the line clearly communicates that there will be a new variable initiated.

var get_all_unicorn_promise = db.get_all_unicorns((unicorn) => {
        unicorn.legs.map((leg) => {
            leg.log('yes')
        })
    }).sort(),
    c = 3

What the hell is the c = 3 doing there right?

3. Not consistent

Consider this:

var a = 1,
    b = 2,
    c = 3

With var-per-variable every declaration follow the same structure. With comma-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 declarations

Other than preference, it seems like majority of notable projects use the var-per-variable notation

Martin Gottweis
  • 2,721
  • 13
  • 27
  • for an example of this ugly style (comma-instead-of-another-var) doing it's thing and confusing people, see https://stackoverflow.com/questions/37332155/confusing-use-of-commas-and-newlines-in-variable-assignment-expression-makes-var – Scott Weaver Jun 01 '19 at 21:45
7

I 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:

But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be enforced with the onevar option.

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
  • 6
    It may be worth noting that Mozilla Javascript (via the `let` construct) *does* have block scope. – BlackVegetable Nov 02 '13 at 01:12
  • 3
    @BlackVegetable `let` can be used in more than just Mozilla JS ([see here](http://caniuse.com/#feat=let)). It is [part of the ES6 specification](http://www.ecma-international.org/ecma-262/6.0/#sec-let-and-const-declarations), but most browsers are still working on implementing features of ES6. – mbomb007 Jan 28 '16 at 16:52
3

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

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • 1
    He's right. Placing variables onto separate lines is recommended in most languages because source control merge algorithms typically work by comparing each line as plain text (not lexical statements within a line). If two people edit the same function, declaring multiple variables on the same line will almost certainly cause a merge conflict, whereas separate lines can almost always be merged automatically. (Regardless if they were declared as separate `var` statements or chained with commas.) – Richard Dingwall Dec 02 '14 at 23:32
  • "He's right." More accurately, Heretic's right. Crockford changed tunes, both in recommendation and in JSLint's code, at some point. It used to demand one `var`, potentially with multiple variables, per block. It now not only supports `let` and `const` (but then properly disallows `var`) but _requires_ a separate declaration for each variable. It's one of JSLint's starkest 180s. – ruffin Jun 23 '21 at 14:30
2

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:

12.2 Variable Statement

Syntax

  VariableStatement :
    var VariableDeclarationList ;

  VariableDeclarationList :
    VariableDeclaration
    VariableDeclarationList , VariableDeclaration

  VariableDeclarationListNoIn :
    VariableDeclarationNoIn
    VariableDeclarationListNoIn , VariableDeclarationNoIn

  VariableDeclaration :
    Identifier Initialiseropt

  VariableDeclarationNoIn :
    Identifier InitialiserNoInopt

  Initialiser :
    = AssignmentExpression
  InitialiserNoIn :
    = AssignmentExpressionNoIn

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 the VariableDeclarations when the script is compiled.

Scott Mermelstein
  • 15,174
  • 4
  • 48
  • 76
2

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:

var 
   one
  ,two
  ,three
  ,four
;

As it's shorter and arguably more readable, no var noise to look at.

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • 23
    keyword on "arguably". If I found this sample in ours it would become `var one, two, three four;` very quickly. Adding lines-for-the-sake-of-lines in Javascript can be dangerous (JS interpreters can insert their own `;`--if you don't anticipate this then you'll quickly find side-effects. Also, leading `,`'s bug me, keywords getting their own line bug me, the `;` on it's own line bugs me. Are you paid by-the-line? – STW Sep 23 '10 at 18:39
  • 8
    @STW - You make automatic semicolon insertion sound like a random thing, subject to the whims of individual browsers, but in reality it only occurs according to a well-defined set of rules and you don't have to worry that it might happen in the middle of your `var` declaration. (Though I agree with you about leading commas, and about `var` and the final semicolon being on their own lines - all three bug me too.) – nnnnnn Feb 29 '12 at 11:10
  • 1
    I don't think this really answers the question, since the question is not about personal preference. – Keith Pinson Mar 20 '14 at 18:14
2

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

rmeador
  • 25,504
  • 18
  • 62
  • 103
  • 1
    Interesting point, but I'm not sure this answers the question of what actual advantages and disadvantages of this *JavaScript* syntax are. – Keith Pinson Mar 20 '14 at 18:12
1

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.

STW
  • 44,917
  • 17
  • 105
  • 161
1

If you are minifying your javascript, there is a fairly large benefit:

var one, two, three, four;

becomes

var a, b, c, d;

Where as

var one;
var two;
var three;
var four;

becomes

var a;
var b;
var c;
var d;

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

Ryan Kinal
  • 17,414
  • 6
  • 46
  • 63
  • 6
    Good minifiers, like the Google Closure Compiler will merge multiple var statements into one: http://img840.imageshack.us/img840/3601/closurecompilerservice.jpg. Therefore this argument stands only if you're using a less smart minifier... which you should't :) – Daniel Vassallo Sep 23 '10 at 19:04
  • 2
    And if you’re gzipping, the repeated `var `s won’t appreciably increase the gzipped file size (if I understand gzipping correctly). – Paul D. Waite Feb 29 '12 at 10:39