Pay attention to your commas
1 min read

Pay attention to your commas

I'm a fan of the comma-separated variable declaration in javascript, ie.

var myVar1 = 1,
    myVar2 = 2,
    myVar3 = 3;

I think it looks better than...

var myVar1 = 1;
var myVar2 = 2;
var myVar3 = 3;

...and on the long run it also helps you save some space (all those extra 'var' declaration tend to add up), although it's somewhat negligeable on a small-scale project.
On top of that, keeping your variables clustered together at the beginning of a function helps you in understanding what's happening there. You can take a quick glance at first line and, if your variables are nicely named, you get a better idea.

However, I just spent close to an hour of debugging trying to fix a very strange bug caused by this way of declaring the variables. What I did was this:

var myVar1 = 1,
    myVar2 = 2
    myVar3 = 3;

Notice the missing comma after myVar2? I didn't :)
That small, small, small error will turn your local myVar3 into a global variable and, in some cases, screw things up. That's because the compiler translates that to

var myVar1 = 1,
    myVar2 = 2;
myVar3 = 3;

In order to avoid such errors, it's a good idea to get the habbit of placing commas before the variable's name

var myVar1 = 1
   ,myVar2 = 2
   ,myVar3 = 3;

You can try to do a test by running the following code and check the results for yourself.

 var a1 = 1,
     b1 = 2
     c1 = 3;

console.log(a1); // returns 'undefined'
console.log(c1); // returns '3'

 var  a2 = 1
     ,b2 = 2
     ,c2 = 3;

console.log(a2); // returns 'undefined'
console.log(c2); // returns 'undefined'