Declaring Multiple Variables in JavaScript

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?


Solution 1:

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 contain the var keyword and semicolon. And every time you add a new declaration, you have to change the semicolon in the old line to a comma.

Solution 2:

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

(function () {
var variable1 = "Hello World!" // semicolon is missed out accidently
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 accidently
    variable2 = "Testing...", // becomes a global variable
    variable3 = 42; // a global variable as well

Solution 3:

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

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

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

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.