Skip to content Skip to sidebar Skip to footer

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 vari

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

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

(function () {
var variable1 = "Hello, World!"// Semicolon is missed out accidentallyvar variable2 = "Testing..."; // Still a local variablevar 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:

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:

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:

ECMAScript 2015 introduced destructuring assignment which works pretty nice:

[a, b] = [1, 2]

a will equal 1 and b will equal 2.

Post a Comment for "Declaring Multiple Variables In Javascript"