1

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.)

1 Answer 1

4

In javascript you can separate expressions by commas and they will execute left to right, returning the value of the far right expression

So yes you can do this in general and the following is legal syntax.

for (i = 0, l = haystack.length; i < l; i++) { ... }

See more about the comma operator here: MDN Docs

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

3 Comments

Thanks Ben! Would there be anything wrong with using a semicolon in the for loop after the i = 0 (instead of a comma)? Do you normally use commas for setting multiple vars (when not using the var keyword), or do you prefer semicolons?
I don't believe that would work within the for loop. You can see the specs for those loops here: developer.mozilla.org/en-US/docs/JavaScript/Reference/… It looks like you can only have 3 statements. Adding an extra would not be valid syntax.
Ah, to answer my own question, it looks like the comma is preferred when in the context of a for loop: for ([initialization]; [condition]; [final-expression]). Found via MDN docs as well. I thought this was also good to know: "The result of [the initialization] expression is discarded".

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.