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?
Another reason to avoid the single statement version (single var) is debugging. If an exception is thrown in any of the assignment lines the stack trace shows only the one line.
If you had 10 variables defined with the comma syntax you have no way to directly know which one was the culprit.
The individual statement version does not suffer from this ambiguity.
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.Use ES6 Destructuring assignment : It will unpack values from arrays, or properties from objects, into distinct variables.
Maybe like this
Except when changing the first or last variable it is easy to maintain and read.
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).
"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."
http://en.wikipedia.org/wiki/Coupling_(computer_programming)
So choose the first one.
It's much more readable when doing it this way:
But takes less space and lines of code this way:
It can be ideal for saving space, but let JavaScript compressors handle it for you.