Declaring multiple variables in 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.
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.
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
}());