Declaring multiple variables in JavaScript

JavascriptVariablesCoding StylePerformanceDeclaration

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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
}());

Solution 3 - Javascript

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.

Solution 4 - Javascript

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.

Solution 5 - Javascript

ECMAScript 2015 introduced destructuring assignment which works pretty nice:

[a, b] = [1, 2]

a will equal 1 and b will equal 2.

Solution 6 - Javascript

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.

Solution 7 - Javascript

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.

Solution 8 - Javascript

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

Solution 9 - Javascript

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.

Solution 10 - Javascript

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.

Solution 11 - Javascript

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

Solution 12 - Javascript

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.

Solution 13 - Javascript

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 */;

Solution 14 - Javascript

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.

Solution 15 - Javascript

As everyone has stated it is largely preference and readability, but I'll throw a comment on the thread since I didn't see others share thoughts in this vein

I think the answer to this question is largely dependent on what variables you're setting and how they're related. I try to be consistent based on if the variables I'm creating are related or not; my preference generally looks something like this:

For unrelated variables

I single-line them so they can be easily moved later; I personally would never declare unrelated items any other way:

const unrelatedVar1 = 1;
const unrelatedVar2 = 2;
const unrelatedVar3 = 3;

If I'm creating new variables I declare as a block -- this serves as a hint that the attributes belong together

const
  x = 1,
  y = 2,
  z = 3
;

// or
const x=1, y=2, z=3;

// or if I'm going to pass these params to other functions/methods
const someCoordinate = {
  x = 1,
  y = 2,
  z = 3
};

this, to me, feels more consistent with de-structuring:

const {x,y,z} = someCoordinate;

where it'd feel clunky to do something like (I wouldn't do this)

const x = someCoordiante.x;
const y = someCoordiante.y;
const z = someCoordiante.z;

If multiple variables are created with the same constructor I'll often group them together also; I personally find this more readable

Instead of something like (I don't normally do this)

const stooge1 = Person("moe");
const stooge2 = Person("curly");
const stooge3 = Person("larry");

I'll usually do this:

const [stooge1, stooge2, stooge3] = ["moe", "curly", "larry"].map(Person);

I say usually because if the input params are sufficiently long that this becomes unreadable I'll split them out.

I agree with other folk's comments about use-strict

Solution 16 - Javascript

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.

Solution 17 - Javascript

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.

Solution 18 - Javascript

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

Solution 19 - Javascript

A person with c background will definitely use the second method

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

the above method is more look like in c language

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSteve HarrisonView Question on Stackoverflow
Solution 1 - JavascriptPaige RutenView Answer on Stackoverflow
Solution 2 - JavascriptKenny KiView Answer on Stackoverflow
Solution 3 - JavascriptJason StackhouseView Answer on Stackoverflow
Solution 4 - Javascriptuser215871View Answer on Stackoverflow
Solution 5 - JavascriptNir NaorView Answer on Stackoverflow
Solution 6 - JavascriptBrian CampbellView Answer on Stackoverflow
Solution 7 - Javascriptjoe nerdanView Answer on Stackoverflow
Solution 8 - JavascriptRohìt JíndalView Answer on Stackoverflow
Solution 9 - JavascriptKevin CrowellView Answer on Stackoverflow
Solution 10 - JavascriptcodelionView Answer on Stackoverflow
Solution 11 - JavascriptWade HarrellView Answer on Stackoverflow
Solution 12 - JavascriptshawnView Answer on Stackoverflow
Solution 13 - Javascriptv1r00zView Answer on Stackoverflow
Solution 14 - JavascriptBeauView Answer on Stackoverflow
Solution 15 - JavascriptSchaltonView Answer on Stackoverflow
Solution 16 - JavascriptMagneView Answer on Stackoverflow
Solution 17 - JavascriptKirill ReznikovView Answer on Stackoverflow
Solution 18 - Javascriptvegemite4meView Answer on Stackoverflow
Solution 19 - JavascriptAjay SahuView Answer on Stackoverflow