362

In JavaScript, it is possible to declare multiple variables like this:

var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;

...or like this:

var variable1 = "Hello, World!",
    variable2 = "Testing...",
    variable3 = 42;

Is one method better/faster than the other?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Steve Harrison
  • 103,209
  • 15
  • 83
  • 71

17 Answers17

373

The first way is easier to maintain. Each declaration is a single statement on a single line, so you can easily add, remove, and reorder the declarations.

With the second way, it is annoying to remove the first or last declaration because they start from the var keyword and finish with the semicolon respectively. Every time you add a new declaration, you have to replace the semicolon in the last old line with a comma.

Kate Orlova
  • 2,793
  • 5
  • 9
  • 28
Paige Ruten
  • 157,734
  • 36
  • 172
  • 191
  • 71
    If you're writing code that you expect to minify or pack later, the second way allows compressors (like the YUI Compressor) to give you a more minified version. If size is a consideration, then I would suggest following as many of JSLint's suggestions as possible. – Lane Aug 18 '11 at 21:48
  • 36
    jslint claims that second way is more righteous but I disagree. – ThatGuy Sep 08 '11 at 04:32
  • 30
    The second way is a micro-optimization. All the var declarations are processed at once, rather than one at a time. This doesn't matter that much in modern browsers/modern computers. – webnesto Apr 14 '12 at 00:19
  • @Lane This may be a stupid question, but, should I assume that all three variables inherently say `var variableX` when only the first one has the `var` prefix and they are comma separated? i.e. are the second two vars global if not preceeded with `var`? – Kristian Feb 08 '13 at 21:21
  • @vol7ron the other variables only become global if a comma is forgotten. In the original question, all 3 variables would be treated in the local scope. – AdamDev Jul 15 '13 at 18:27
  • @AdamDev: that is correct; I've withdrawn my full comment, though I have seen issues with scoping in this manner in one of the browsers -- they all appear to be working now – vol7ron Jul 16 '13 at 04:22
  • 1
    @Kristian: No, the latter variables also live in the same closure, and they are not global. Notice that the declaration is a single statement. – 0xc0de Jul 16 '13 at 08:05
  • The second way in fact is more efficient. – 0xc0de Jul 16 '13 at 08:06
  • 18
    @0xc0de: I would like to see the proof of declaring all the variables in one statement as "efficient". If you are only measuring efficiency as a matter of the few bytes saved, then maybe. But if you take into account readability and maintainability, I think you'll find that premature optimization is usually the wrong way to go, especially since modern browsers will collect and initialize all the variables in a scope on a pre-execution pass. Personally, I find having variables all declared in a single line or statement to make quickly understanding code harder and more error prone. – ogradyjd Sep 03 '13 at 11:51
  • 9
    Concerning efficiency, both uglifyjs and the google closure compiler will automatically squash sequential var statements into one, rendering that point moot (as far as I can tell YUI will not do this, however I haven't tested extensively). – bhuber Feb 17 '14 at 15:58
  • 3
    Just want to add a link to a very interesting blog post by Ben Alman, that eventually convinced me to used multiple var statements: http://benalman.com/news/2012/05/multiple-var-statements-javascript/ – clement g Jul 22 '14 at 15:39
  • 2
    FWIW, when a team I was on tried the single-var approach, we seemed to run into more merge problems in git. This kind of makes sense, since you have to edit more lines of code when you change anything, as the Ben Alman article points out. We switched back to using multiple `var`s. – Chris Jaynes Aug 06 '14 at 14:28
  • 1
    I created a simple jsperf to see what difference it made to me (Chrome 64-bit on Ubuntu 64-bit) and I was surprised to see that multiple var keywords was actually nominally faster. But they're both so close that it really should be a matter of personal preference. I personally find multiple var keywords to be more maintainable and less error prone. Link to jsperf: http://jsperf.com/var-declaractions-single-or-multiple. The jsperf posted under the OP's question (http://jsperf.com/multi-vars-vs-single-var) shows, to me, that a single var is 6% slower than multiple vars. My jsperf is minimal. – bmacnaughton Jan 25 '15 at 17:10
223

Besides maintainability, the first way eliminates possibility of accident global variables creation:

(function () {
var variable1 = "Hello, World!" // Semicolon is missed out accidentally
var variable2 = "Testing..."; // Still a local variable
var variable3 = 42;
}());

While the second way is less forgiving:

(function () {
var variable1 = "Hello, World!" // Comma is missed out accidentally
    variable2 = "Testing...", // Becomes a global variable
    variable3 = 42; // A global variable as well
}());
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kenny Ki
  • 3,170
  • 1
  • 21
  • 30
  • 4
    Good point. If they're short, then writing on a single line will avoid this problem: `var variable1 = "Hello World!", variable2 = "Testing...", variable3 = 42;`. A missing `,` will crash, but I agree it's risky – Aram Kocharyan Jan 16 '12 at 04:18
  • 16
    If you're using strict mode you won't be able to create globals like this anyway. – Danyal Aytekin Oct 24 '12 at 10:42
  • 1
    I'm a fan of declaring multiple variables on a single line because I think it looks cleaner. That said, accidentally declaring global variables is a real danger. While hunting down memory leaks I have come across multiple instances where I accidentally declared several global variables at once because I used a semicolon instead of a comma. – smabbott Mar 06 '13 at 15:26
  • +1 just spend half of the day and even started to wondering why there is undocumented difference between these two declarations. Then read this answer, checked code super carefully and found the mistake. Need a holiday... – Giedrius Apr 29 '13 at 21:50
  • @Giedrius: it is not an undocumented feature. Semi-colons (;) are not mandatory in javascript and if you don't use the 'var' keyword the variable is considered to be global (creating it if it does not exist). In the example `var variable1 = "Hello World!" // comma is missed out accidently variable2 = "Testing...", // becomes a global variable variable3 = 42; // a global variable as well the first assignment` is equivalent to `var variable1 = "Hello World!"; // with semi-colon` whence the "undocumented" behaviour. – user2560528 Jul 08 '13 at 15:51
  • 1
    My text editor gives me a `Possible Fatal Error` if I miss a coma, hurray for me! –  Feb 03 '15 at 03:35
37

It's much more readable when doing it this way:

var hey = 23;
var hi = 3;
var howdy 4;

But takes less space and lines of code this way:

var hey=23,hi=3,howdy=4;

It can be ideal for saving space, but let JavaScript compressors handle it for you.

Jason Stackhouse
  • 1,558
  • 2
  • 14
  • 19
33

It's common to use one var statement per scope for organization. The way all "scopes" follow a similar pattern making the code more readable. Additionally, the engine "hoists" them all to the top anyway. So keeping your declarations together mimics what will actually happen more closely.

spencer.sm
  • 14,681
  • 8
  • 67
  • 76
  • 6
    You can keep the declarations together without making them sharing the same 'var' declaration. I understand and accept the explanations given at jslint (your link) but I don't share the conclusion. As said above, it is more matter of style than anything else. In the Java world (among others), the reverse (one declaration per line) is recommended for readability. – PhiLho May 19 '11 at 12:34
  • More readable? The only reason people put them on one line is the JS-specific reason you mentioned: JS moves all the declarations to the top. If it didn't do that, we would all be declaring our vars closest to the point where they are used. – Danyal Aytekin Oct 24 '12 at 10:45
  • @vol7ron that is not the case, and is a gross misunderstanding of the `var` statement. the exact opposite is true. [see the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) and [this example](http://jsbin.com/AdILOKi/2/edit?console,js) – jackweirdy Sep 17 '13 at 12:58
  • @jackweirdy you are correct and it was the case, poor implementation, or bug in older browsers. I've since deleted my comment. – vol7ron Sep 17 '13 at 21:12
21

ECMAScript 2015 introduced destructuring assignment which works pretty nice:

[a, b] = [1, 2]

a will equal 1 and b will equal 2.

Calculuswhiz
  • 3,244
  • 9
  • 21
  • 35
Nir Naor
  • 359
  • 3
  • 5
  • it doesn't answer the question, but it can be a better alternative to both described approaches. – svarog Sep 22 '16 at 11:23
  • 1
    I think that your approach is not really viable in case if you have long lists of variables. It is hard to say to which variable which value is related and also you don't have protection from errors is case of bad merge during which you accidentally could remove one element from an array. Example: ```let [aVar, bVar, cVar, xVar, yVar, zVar] = [10, 20, 30, 40, 50];``` So, personally I do not recommend it. – Kirill Reznikov May 22 '17 at 10:10
  • 1
    handy if you want to set a lot of variables with the same values though. Using to reset to zero in a loop for instance. – Nick Nov 19 '18 at 10:08
  • Yes! this is what I was looking for. Especially if you want to define a two dimensional pair, or multi-dimensional values, yet not arrays. – Eugene Kardash Aug 15 '19 at 00:02
16

It's just a matter of personal preference. There is no difference between these two ways, other than a few bytes saved with the second form if you strip out the white space.

Brian Campbell
  • 289,867
  • 55
  • 346
  • 327
  • The second one saves a couple of bytes. – Sophie Alpert Mar 29 '09 at 04:40
  • Ben Alpert: How do you figure? – Josh Stodola Mar 29 '09 at 04:47
  • If you strip out the whitespace, than the 'var foo="hello",bar="world";' declaration takes up fewer characters than 'var foo="hello";var bar="world";' If you have a popular site, saving a few bytes on the JS can help (you'd also want to minimize variable names, etc) – Brian Campbell Mar 29 '09 at 04:52
  • I see this the saved bytes as irrelevant at this time, due to the rise of JavaScript minifiers, notably the Google Closer Compiler's (so-called) simple mode. – 700 Software Mar 27 '12 at 16:08
  • This is an incorrect statement - there is a difference in how the runtime engine processes them (at least in older browsers, not sure about modern browsers). – webnesto Apr 14 '12 at 00:27
  • @webnesto Can you provide some evidence to back that up? – Brian Campbell Apr 14 '12 at 01:04
  • @BrianCampbell - I could've sworn I read it in High Performance Javascript by Zakas, but I'm having a hard time locating it right now. I'll keep my eye open and check back with a reference when I've got it. It isn't a major difference anyway - just a performance one from what I recall (and a tiny micro-performance difference at that). – webnesto Apr 14 '12 at 03:06
  • 1
    @webnesto there's never any performance from syntax when the semantics of the syntax are the same. One will not execute code right away but first parse it and do semantic analysis - this is where both of the declaration styles are equalized. – Esailija Aug 04 '13 at 16:09
  • > A few bytes More like a couple bits. –  Feb 03 '15 at 03:38
16

Maybe like this

var variable1 = "Hello, World!"
, variable2 = 2
, variable3 = "How are you doing?"
, variable4 = 42;

Except when changing the first or last variable, it is easy to maintain and read.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
joe nerdan
  • 193
  • 1
  • 2
  • 6
    Typically, using comma-first, the semicolon goes on a new line to prevent that issue. var variable1 = "hello world"\n , variable2 = 2\n , variable3 = "how are you doing"\n , variable4 = 42\n ;\n – BrianFreud Jan 31 '12 at 04:08
  • 3
    This is Haskell syntax. I feel that somehow it is not recommended/common practice in javascript – shamanSK Jun 21 '18 at 10:38
13

Use the ES6 destructuring assignment: It will unpack values from arrays, or properties from objects, into distinct variables.

let [variable1 , variable2, variable3] =
["Hello, World!", "Testing...", 42];

console.log(variable1); // Hello, World!
console.log(variable2); // Testing...
console.log(variable3); // 42
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Rohit Jindal
  • 11,704
  • 11
  • 56
  • 92
12
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;

is more readable than:

var variable1 = "Hello, World!",
    variable2 = "Testing...",
    variable3 = 42;

But they do the same thing.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kevin Crowell
  • 9,476
  • 4
  • 32
  • 51
7

My only, yet essential, use for a comma is in a for loop:

for (var i = 0, n = a.length; i < n; i++) {
  var e = a[i];
  console.log(e);
}

I went here to look up whether this is OK in JavaScript.

Even seeing it work, a question remained whether n is local to the function.

This verifies n is local:

a = [3, 5, 7, 11];
(function l () { for (var i = 0, n = a.length; i < n; i++) {
  var e = a[i];
  console.log(e);
}}) ();
console.log(typeof n == "undefined" ?
  "as expected, n was local" : "oops, n was global");

For a moment I wasn't sure, switching between languages.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
codelion
  • 125
  • 1
  • 4
7

Although both are valid, using the second discourages inexperienced developers from placing var statements all over the place and causing hoisting issues. If there is only one var per function, at the top of the function, then it is easier to debug the code as a whole. This can mean that the lines where the variables are declared are not as explicit as some may like.

I feel that trade-off is worth it, if it means weaning a developer off of dropping 'var' anywhere they feel like.

People may complain about JSLint, I do as well, but a lot of it is geared not toward fixing issues with the language, but in correcting bad habits of the coders and therefore preventing problems in the code they write. Therefore:

"In languages with block scope, it is usually recommended that variables be declared at the site of first use. 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." - http://www.jslint.com/lint.html#scope

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Wade Harrell
  • 81
  • 1
  • 1
7

Another reason to avoid the single statement version (single var) is debugging. If an exception is thrown in any of the assignment lines the stack trace shows only the one line.

If you had 10 variables defined with the comma syntax you have no way to directly know which one was the culprit.

The individual statement version does not suffer from this ambiguity.

shawn
  • 165
  • 2
  • 7
6

I think it's a matter of personal preference. I prefer to do it in the following way:

   var /* Variables */
            me = this, that = scope,
            temp, tempUri, tempUrl,
            videoId = getQueryString()["id"],
            host = location.protocol + '//' + location.host,
            baseUrl = "localhost",
            str = "Visit W3Schools",
            n = str.search(/w3schools/i),
            x = 5,
            y = 6,
            z = x + y
   /* End Variables */;
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
v1r00z
  • 768
  • 9
  • 18
5

The maintainability issue can be pretty easily overcome with a little formatting, like such:

let
  my_var1 = 'foo',
  my_var2 = 'bar',
  my_var3 = 'baz'
;

I use this formatting strictly as a matter of personal preference. I skip this format for single declarations, of course, or where it simply gums up the works.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Beau
  • 191
  • 1
  • 4
  • What is the gist of your formatting? `let` and the semicolon on lines of their own? Or something else? In what way does it help with the maintainability issue? What is the maintainability issue? (These are not rhetorical questions.) The best response would be [editing your answer](https://stackoverflow.com/posts/55972585/edit) (***without*** "Edit:", "Update:" or similar), not here in comments. – Peter Mortensen Oct 30 '20 at 07:45
2

The concept of "cohesion over coupling" can be applied more generally than just objects/modules/functions. It can also serve in this situation:

The second example the OP suggested has coupled all the variables into the same statement, which makes it impossible to take one of the lines and move it somewhere else without breaking stuff (high coupling). The first example he gave makes the variable assignments independent of each other (low coupling).

From Coupling:

Low coupling is often a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability.

So choose the first one.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Magne
  • 14,749
  • 8
  • 57
  • 77
  • 1
    I fail to see how this is related to coupling or cohesion. Care to elaborate? – Edson Medina Jan 27 '15 at 17:31
  • The second example the OP suggested has coupled all the variables into the same statement, which makes it impossible to take one of the lines and move it somewhere else without breaking stuff (high coupling). The first example he gave makes the variable assignments independent of each other (low coupling). – Magne Jan 27 '15 at 18:17
  • Coupling is about interdependency between different modules/objects/functions, NOT lines of code! – Edson Medina Jan 27 '15 at 23:35
  • 1
    Originally it was about modules, yes, but the concept can be applied more generally, as even your own inclusion of objects/functions into the definition shows. – Magne Jan 28 '15 at 09:08
1

I believe that before we started using ES6, an approach with a single var declaration was neither good nor bad (in case if you have linters and 'use strict'. It was really a taste preference. But now things changed for me. These are my thoughts in favour of multiline declaration:

  1. Now we have two new kinds of variables, and var became obsolete. It is good practice to use const everywhere until you really need let. So quite often your code will contain variable declarations with assignment in the middle of the code, and because of block scoping you quite often will move variables between blocks in case of small changes. I think that it is more convenient to do that with multiline declarations.

  2. ES6 syntax became more diverse, we got destructors, template strings, arrow functions and optional assignments. When you heavily use all those features with single variable declarations, it hurts readability.

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Kirill Reznikov
  • 1,939
  • 3
  • 14
  • 26
0

I think the first way (multiple variables) is best, as you can otherwise end up with this (from an application that uses KnockoutJS), which is difficult to read in my opinion:

    var categories = ko.observableArray(),
        keywordFilter = ko.observableArray(),
        omniFilter = ko.observable('').extend({ throttle: 300 }),
        filteredCategories = ko.computed(function () {
            var underlyingArray = categories();
            return ko.utils.arrayFilter(underlyingArray, function (n) {
                return n.FilteredSportCount() > 0;
            });
        }),
        favoriteSports = ko.computed(function () {
            var sports = ko.observableArray();
            ko.utils.arrayForEach(categories(), function (c) {
                ko.utils.arrayForEach(c.Sports(), function (a) {
                    if (a.IsFavorite()) {
                        sports.push(a);
                    }
                });
            });
            return sports;
        }),
        toggleFavorite = function (sport, userId) {
            var isFavorite = sport.IsFavorite();

            var url = setfavouritesurl;

            var data = {
                userId: userId,
                sportId: sport.Id(),
                isFavourite: !isFavorite
            };

            var callback = function () {
                sport.IsFavorite(!isFavorite);
            };

            jQuery.support.cors = true;
            jQuery.ajax({
                url: url,
                type: "GET",
                data: data,
                success: callback
            });
        },
        hasfavoriteSports = ko.computed(function () {
            var result = false;
            ko.utils.arrayForEach(categories(), function (c) {
                ko.utils.arrayForEach(c.Sports(), function (a) {
                    if (a.IsFavorite()) {
                        result = true;
                    }
                });
            });
            return result;
        });
Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
vegemite4me
  • 5,718
  • 4
  • 50
  • 70