In JavaScript, it is possible to declare multiple variables like this:
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var
I think it's a matter of personal preference. I prefer to do it in the following way:
var /* Variables */
me = this, that = scope,
temp, tempUri, tempUrl,
videoId = getQueryString()["id"],
host = location.protocol + '//' + location.host,
baseUrl = "localhost",
str = "Visit W3Schools",
n = str.search(/w3schools/i),
x = 5,
y = 6,
z = x + y
/* End Variables */;
ECMAScript 2015 introduced destructuring assignment which works pretty nice:
a
will equal 1
and b
will equal 2
.
The concept of "cohesion over coupling" can be applied more generally than just objects/modules/functions. It can also serve in this situation:
The second example the OP suggested has coupled all the variables into the same statement, which makes it impossible to take one of the lines and move it somewhere else without breaking stuff (high coupling). The first example he gave makes the variable assignments independent of each other (low coupling).
From Coupling:
Low coupling is often a sign of a well-structured computer system and a good design, and when combined with high cohesion, supports the general goals of high readability and maintainability.
So choose the first one.
The maintainability issue can be pretty easily overcome with a little formatting, like such:
let
my_var1 = 'foo',
my_var2 = 'bar',
my_var3 = 'baz'
;
I use this formatting strictly as a matter of personal preference. I skip this format for single declarations, of course, or where it simply gums up the works.
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
}());
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.