What's the less error prone approach to declare variables in JavaScript?
var a;
var b;
var c;
or
var a,
b,
c;
jQuery and Dojo use the second approach and personally that's my favorite in terms of code legibility, the problem is that I find it harder to debug.
Example 1:
var a,
b,
c; // oops.. semicolon instead of comma
d,
e;
Example 2:
When searching for a certain variable in the project, var
stands out better that the variable is being declared.
EDIT: The original examples were wrong, i've made a mistake when copying and pasting. The code is already updated, sorry for the incovenient.
Multiple variable declarations (rather than combined) are less error prone, for the reasons you mentioned. However, combined declarations have some other advantages:
var
keywords per scope.var
keyword minifies better than many, for obvious reasons.On the flipside, as you mentioned mistakes can be made with combined variable declarations, and they can be awkwardly represented in a diff.
As long as you keep a consistent style of variable declaration throughout the project, the style you choose should not really matter.
I prefer your second approach of using just one var
keyword. Recently I have taken it a step further and instantiate types onto each variable to help me prevent unintended type recasting later. An example is:
var a = 0,
b = 0,
c = {},
d = [],
f = "";
I supply an actual value here if I have a value to supply at this point. If not I supply the following dummy values:
0
for number types[]
for array{}
for object literal and DOM nodes""
for stringfunction () {return;}
for functionsfalse
for booleanIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With