Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the most idiomatic way to declare a list of local javascript variables?

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;
like image 732
Ben Lee Avatar asked Nov 17 '25 06:11

Ben Lee


1 Answers

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.

like image 94
Matt Avatar answered Nov 19 '25 20:11

Matt