What is the advantage of initializing multiple javascript variables with the same var keyword?

There’s a slight advantage with the size of the javascript that is sent to the browser; Google’s Closure compiler in ‘whitespace only’ mode will compile the single var version into:

var x=some.initialization.method(),y=something.els(),z;

and the multi as:

var x=some.initialization.method();var y=something.els();var z;

I changed your else to els so that it would compile.

This isn’t a massive gain (especially if you are also compressing the files), and the ‘simple’ compilation mode will do this for you anyway, so I probably wouldn’t be too concerned about it unless you can find more compelling reasons.

One reason you may not want to do this is that if you accidentally use a semicolon instead of a comma you’ve just found a global.

Leave a Comment