3

I know all of the below versions work, and I've see them all in the wild to varying degrees. Just wondering if there is one fairly standard idiomatic way among these (are there any references to support this)?

Version (1):

var x = 1;
var y = 2;
var z = 3;

Version (2):

var x = 1,
    y = 2,
    z = 3;

Version (3):

var x = 1, y = 2, z = 3;
4
  • 2
    jslint prefers the single var statement (version 2). Crockford advocates for it. Commented Dec 2, 2011 at 19:03
  • docstore.mik.ua/orelly/webprog/jscript/ch04_02.htm Commented Dec 2, 2011 at 19:04
  • (2) and (3) are the same. Or are you asking about whitespace best practices too? Commented Dec 2, 2011 at 19:26
  • @RoatinMarth, yes I was looking for most idiomatic whitespace too. Commented Dec 2, 2011 at 20:12

3 Answers 3

3

Ideally, it should be the second or third, as they prompt you to declare all your variables in the same place (i.e. at the top of the script). Word had it that it was also slighty quicker, but my JSPerf gives them the same results in IE9 and Chrome 15.

However, I find the first easier to a) read, and b) easier to maintain; it's easy to miss one ,, or forget to change the last ; to a , when you add a new variable, and you end up leaking it into the global scope.

Sign up to request clarification or add additional context in comments.

2 Comments

This seems to be a clear summary of the wildly opinionated and contradictory things I've seen all over the web. Thanks!
Interestingly, I've seen #3 advocated before, and never understood why anyone would prefer that form, but in light of your answer I have a theory. It (a) encourages all variable declarations in the same place and (b) is not likely someone will screw up the punctuation marks. So it has something each of the others has (and something each of the others lack). But I find it by far the hardest to read. So I guess they all have advantages.
3

6 of one, half a dozen of another... it's all the same.

Comments

1

They are all 'valid' but I find version 2 to be the most used.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.