views:

2617

answers:

4

Hello,

In JavaScript, it is possible to declare multiple variables like this:

var variable1 = "Hello World!";
var variable2 = "Testing...";
var variable3 = 42;

...or like this:

var variable1 = "Hello World!",
    variable2 = "Testing...",
    variable3 = 42;

Is one method better/faster than the other?

Thanks,

Steve

+4  A: 

It's just a matter of personal preference. There is no difference between these two ways, other than a few bytes saved with the second form if you strip out the white space.

Brian Campbell
The second one saves a couple of bytes.
Ben Alpert
Ben Alpert: How do you figure?
Josh Stodola
If you strip out the whitespace, than the 'var foo="hello",bar="world";' declaration takes up fewer characters than 'var foo="hello";var bar="world";' If you have a popular site, saving a few bytes on the JS can help (you'd also want to minimize variable names, etc)
Brian Campbell
+1  A: 
var variable1 = "Hello World!";
var variable2 = "Testing...";
var variable3 = 42;

is more readable than:

var variable1 = "Hello World!",
    variable2 = "Testing...",
    variable3 = 42;

But they do the same thing.

Kevin Crowell
Uses less "file space"? I think you have some explaining to do.
Josh Stodola
+9  A: 

The first way is easier to maintain. Each declaration is a single statement on a single line, so you can easily add, remove, and reorder the declarations.

With the second way, it is annoying to remove the first or last declaration because they contain the var keyword and semicolon. And every time you add a new declaration, you have to change the semicolon in the old line to a comma.

yjerem
Good point! Thanks!
Steve Harrison
+2  A: 

It's common to use one var statement per scope for organization. The way all "scopes" follow a similar pattern making the code more readable. Additionally, the engine "hoists" them all to the top anyway. So keeping your declarations together mimics what will actually happen more closely.