Advertisement
Advertisement


Declaring Multiple Variables in JavaScript


Question

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?

2015/11/12
1
344
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.

2020/07/25
353
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.

2016/02/25

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.

2014/01/24

ECMAScript6 introducted destructuring assignment which works pretty nice:

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

2018/10/26

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.

2011/12/19

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.

2009/03/29

Source: https://stackoverflow.com/questions/694102
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]