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

It's just a matter of personal preference. There is no difference between these two ways, other than a few bytes saved with the second form if you strip out the white space.

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

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

(function () {
var variable1 = "Hello World!" // semicolon is missed out accidently
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 accidently
    variable2 = "Testing...", // becomes a global variable
    variable3 = 42; // a global variable as well
}());
查看更多
何处买醉
4楼-- · 2019-01-01 00:46
var variable1 = "Hello World!";
var variable2 = "Testing...";
var variable3 = 42;

is more readable than:

var variable1 = "Hello World!",
    variable2 = "Testing...",
    variable3 = 42;

But they do the same thing.

查看更多
梦该遗忘
5楼-- · 2019-01-01 00:50

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.

查看更多
登录 后发表回答