JavaScript 变量定义: 逗号与分号

在声明一组变量而不是分号时使用逗号有什么区别和/或优点(如果有的话)。

例如:

var foo = 'bar', bar = 'foo';

VS

var foo = 'bar';
var bar = 'foo';

我知道,如果您在第一个示例中指定第一个变量的 var关键字,那么它将在所有变量中持久存在,因此它们在作用域方面都会产生相同的最终结果。这仅仅是个人偏好,还是这两种方式都有性能上的好处?

41741 次浏览

No performance benefit, just a matter of personal choice and style.

The first version is just more succinct.


Update:

In terms of the amount of data going over the wire, of course less is better, however you would need a hell of a lot of removed var declarations in order to see a real impact.

Minification has been mentioned as something that the first example will help with for better minification, however, as Daniel Vassallo points out in the comments, a good minifier will automatically do that for you anyways, so in that respect no impact whatsoever.

I don't think there's any noticeable difference, as far as I'm concerned it's just personal preference.

I hate having multiple var declarations so I usually do:

var
one
,two
,three
,four
;

As it's shorter and arguably more readable, no var noise to look at.

The first saves a few characters--so there is a very small saving in terms of the JS filesize and therefore bandwidth consumption. The only time this would become noticable would be in extreme cases.

I prefer the second version (each has its own var). I think that's because I come from a C++ background. In C++, you can declare variables like you do in your first example, but it is frowned upon (it easily leads to mistakes when you're trying to create pointers that way).

If you are minifying your javascript, there is a fairly large benefit:

var one, two, three, four;

becomes

var a, b, c, d;

Where as

var one;
var two;
var three;
var four;

becomes

var a;
var b;
var c;
var d;

That's an additional three instances of var, which can add up over time.

See The "A List Apart" article series "Better Javascript Minification" Part 1 and Part 2

As others have noted, it is a style preference. JSLint might tell you to only have one var per function (if you use the "Good Parts"). Thus if using JSLint to check your code (not a bad idea, IMHO), you'll end up using the first format more than the latter.

On the other hand, the same author, Douglas Crockford, says to put each variable in its own line in his coding conventions. So you may want to uncheck the "All one var per function" checkbox in JSLint if you use it. ;-)

I agree with the other answerers that this is mainly a matter of personal style. But to bring an "Authoritative" opinion into the discussion, this is what Douglas Crockford says on the website of the popular JSLint tool:

But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be enforced with the onevar option.

Since I don't see any references to it, here is a link to the ECMA-262 specification, which is the underlying spec for JavaScript. The grammar from that page says:

12.2 Variable Statement


Syntax


VariableStatement :
var VariableDeclarationList ;


VariableDeclarationList :
VariableDeclaration
VariableDeclarationList , VariableDeclaration


VariableDeclarationListNoIn :
VariableDeclarationNoIn
VariableDeclarationListNoIn , VariableDeclarationNoIn


VariableDeclaration :
Identifier Initialiseropt


VariableDeclarationNoIn :
Identifier InitialiserNoInopt


Initialiser :
= AssignmentExpression
InitialiserNoIn :
= AssignmentExpressionNoIn

What you can glean from this is using commas or not doesn't matter. Either way, it ends up being parsed as a VariableDeclaration and is treated exactly the same. There should be no difference to how the script engine treats the two declarations. The only differences would be ones already mentioned in other answers - saving more space and practically immeasurable differences in the amount of time it takes to apply the grammar to find all the VariableDeclarations when the script is compiled.

After reading Crockford and others, I started to chain my variables with comma exclusively. Then later, I really got annoyed by the Chrome DevTools debugger that wouldn't stop at variable definitions with comma. For the debugger, variable definitions chained with comma are a single statement, while multiple var statements are multiple statements at which the debugger can stop. Therefore, I switched back from:

var a = doSomethingA,
b = doSomethignB,
c = doSomethingC;

To:

var a = doSomethingA;
var b = doSomethignB;
var c = doSomethingC;

By now, I find the second variant much cleaner, not to mention its advantage of solving the debugger issue.

The "less code through the wire" argument is not persuasive, as there are minifiers.

I prefer the var-per-variable notation:

var a = 2
var b = 3

because the other comma-instead-of-another-var notation have these three shortcomings:

1. Hard to maintain
Consider this code:

var a = 1,
b = mogrify(2),
c = 3

But hey, what does the mogrify do? Let's print b to find out:

var a = 1,
b = mogrify(2),
console.log(b)
c = 3

breaks stuff

2. Hard to read

The var in the begging of the line clearly communicates that there will be a new variable initiated.

var get_all_unicorn_promise = db.get_all_unicorns((unicorn) => {
unicorn.legs.map((leg) => {
leg.log('yes')
})
}).sort(),
c = 3

What the hell is the c = 3 doing there right?

3. Not consistent

Consider this:

var a = 1,
b = 2,
c = 3

With var-per-variable every declaration follow the same structure. With comma-instead-of-another-var the first variable is declared in different way than others. If you decide to, say, move the first variable inside a for cycle, you will have to add var to the middle of declarations

Other than preference, it seems like majority of notable projects use the var-per-variable notation