Declaring Multiple Variables in JavaScript

2019-01-01 00:22发布

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?

16条回答
心情的温度
2楼-- · 2019-01-01 00:30

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.

查看更多
初与友歌
3楼-- · 2019-01-01 00:33

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.

查看更多
一个人的天荒地老
4楼-- · 2019-01-01 00:37

Use ES6 Destructuring assignment : It will unpack values from arrays, or properties from objects, into distinct variables.

let [variable1 , variable2, variable3] = 
["Hello World!", "Testing...", 42];

console.log(variable1); // Hello World!
console.log(variable2); // Testing...
console.log(variable3); // 42

查看更多
若你有天会懂
5楼-- · 2019-01-01 00:38

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.

查看更多
情到深处是孤独
6楼-- · 2019-01-01 00:39

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.

查看更多
孤独寂梦人
7楼-- · 2019-01-01 00:41

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.

查看更多
登录 后发表回答