Declaring Multiple Variables in JavaScript


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?

11/12/2015 1:25:46 PM

Accepted Answer

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.

7/25/2020 7:56:30 AM

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.


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.


ECMAScript6 introducted destructuring assignment which works pretty nice:

[a, b] = [1, 2] a will equal 1 and b will equal 2.


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.


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.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]