Debate: combined vs independent variable declaration in js

1 minute read

It is regarded as good practice to declare all variables at the top. It is believed that this practice will make it easier while searching for variable declarations and may also help in avoiding multiple declarations in a long file.

var someItem = 'some string';
var anotherItem = 'another string';
var oneMoreItem = 'one more string';

And it is regarded best practice to omit the var keyword and use commas instead. I doubt there’s any real speed improvements here, but it cleans up your code a bit.

var someItem = 'some string',
    anotherItem = 'another string',
    oneMoreItem = 'one more string';

update: This practice is preferred by jshint. ref: combine this with the previous ‘var’ statement

But there is a huge debate regarding this. Let’s look at a sample code below:

var someItem = 'some string'
    anotherItem = 'another string',
    oneMoreItem = 'one more string';

Did you catch the problem above? A lot of people wouldn’t - it’s easy to miss it at first glance. While adding the initial assignments, we “accidentally” lost a comma at the end of the someItem declaration.

But that typo isn’t as interesting as the bug it’ll cause. In JavaScript, semicolons should be added at the end of every statement, but they’re not required. The code above will generate no error messages, no warnings…but it will create a serious bug.

Because the line var someItem = 'some string' is valid JavaScript even without the trailing comma, the parser will go ahead and “insert” a semicolon for you. By doing this, it effectively interprets the code as:

var someItem = 'some string';
    anotherItem = 'another string',
    oneMoreItem = 'one more string';

This breaks the anotherItem and oneMoreItem declarations into a separate statement, and these are now variable declarations without the var keyword. Those variables will now be ejected into the global namespace, regardless of how you tried to scope them.

References:

Categories:

Updated:

Leave a Comment