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
Because the line
var someItem = 'some string'; anotherItem = 'another string', oneMoreItem = 'one more string';
This breaks the
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.