Reading the code of many javascript libraries, I see that many developers use to set variables as soon as they were created them.
var i = 0,
var c = 0;
I prefer instead to defined vars after created them.
var i,
c;
i = 0;
c = 0;
But there might be an explanation about why this or that way?
It’s purely style. Some people prefer to have their declarations isolated from initialization, others like to do it in one. To the JavaScript engine, they’re actually identical, because it handles
varprior to the first line of code of the function actually executing. (Note how that is different from some other languages.) That is, it quite literally treats your two examples identically: First it createsiandcwith the valueundefined, and only later when it starts executing the step-by-step code of the function does it setito 0 and thencto 0. (This is covered in some depth in Section 10.4.3 and Section 10.5 of the spec.)For me, as long as I stick with simple values, I like to do them in one (although I always used to be a “purist” about keeping them separate; I did a lot of silly things when I was younger). But I try to avoid complex logic in the initialization. Sometimes I find I’ve written half my function as a series of comma-delimited statements starting with
var, and that starts to get hard to read and maintain so I tend to pull them out at that point.On the other hand, a reason to keep them separate is it gives you plenty of room to comment them. 🙂