I've seen many examples of:
var foo = 1, bar = 2, baz = 3;
But, can I do the same without var? Example:
// Declare at top of block for readability's sake:
var foo, bar, baz;
// ... stuff here ...
// Later in script, I finally get around to initializing above vars:
foo = 1, bar = 2, baz = 3; // Is using commas without var legal?
In other words, is it legal in javascript to have a line where I initialize/set multiple vars without the var keyword? I have not been able to find any definitive documentation on whether or not this is allowed and/or well supported.
The alternative would be:
foo = 1; bar = 2; baz = 3;
Here's the real world situation that prompted my question:
for (var i = 0, l = haystack.length; i < l; i++) { ... }
... I'd like to move the varible delcaration inside the for loop to the top level of the parent block, like:
var i, l;
// ... stuff here ...
for (i = 0, l = haystack.length; i < l; i++) { ... }
... But I've only ever used the commas when using var at the beginning of the statement. Is the above legal(?), or should it be:
var i, l;
// ... stuff here ...
for (i = 0; l = haystack.length; i < l; i++) { ... }
(Note the added semicolon.)