ldsenow ldsenow - 1 year ago 92
Javascript Question

Why single var is good in javascript?

Can anyone tell me why use one var declaration for multiple variables and declare each variable on a newline consider is a good programming behavior?

// bad
var items = getItems();
var goSportsTeam = true;
var dragonball = 'z';

// good
var items = getItems(),
goSportsTeam = true,
dragonball = 'z';

Answer Source

It is not considered 'good' or 'bad'. It's a matter of preference.

The guy who built the code quality tool JSLint, Douglas Crockford likes it.

One 'advantage' it might have is that it avoids the possibility of variable hoisting. In JavaScript all var declarations move to the top of their scope automatically.

Here is why Crockford thinks the second option is better:

In languages with block scope, it is usually recommended that variables be declared at the site of first use. But because JavaScript does not have block scope, it is wiser to declare all of a function's variables at the top of the function. It is recommended that a single var statement be used per function. This can be declined with the vars option.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download