Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript code conventions - variable declaration [closed]

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.

like image 896
Diogo Cardoso Avatar asked Mar 17 '12 01:03

Diogo Cardoso


2 Answers

Multiple variable declarations (rather than combined) are less error prone, for the reasons you mentioned. However, combined declarations have some other advantages:

  • JSLint and possibly other linters will complain about multiple var keywords per scope.
  • A single var keyword minifies better than many, for obvious reasons.
  • Combining declarations forces you to declare the variables in one place, probably close to the beginning of the function they reside in, which is considered good practice.

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.

like image 123
Dagg Nabbit Avatar answered Sep 28 '22 08:09

Dagg Nabbit


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 string
  • function () {return;} for functions
  • false for boolean
  • for this purpose I don't worry about pre-assigning types for Math, Date, or RegExp types.
like image 39
austincheney Avatar answered Sep 28 '22 07:09

austincheney