Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Single line 'var' declarations, or one per line? [closed]

I'm looking at Douglas Crockford's Code Conventions for JavaScript document, and he's saying that vars should be alphabetical, and one per line.

var a;                  // array of class names
var c = node.className; // the node's classname
var i;                  // loop counter

However, the jsLint (and jsHint) standard is to declare them on a single line, and it throws this error if done Crockford's way

too many var statements

Therefore, jsLint wants it done like this.

var a, c = node.className, i;

This seems quite contradictory to me, and though probably quite minute in the overall scope of programming, I'm hoping to get this right before I get it wrong.

What is the generally accepted practice when declaring JavaScript vars?

like image 944
Chase Florell Avatar asked Feb 09 '12 21:02

Chase Florell


People also ask

How many variables can we declare at a time in JavaScript?

We can also declare two variables and copy data from one into the other.

Can you declare variables on the same line in Java?

Java static code analysis | convention: Multiple variables should not be declared on the same line.

How do you declare more than one variable?

Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values. If more than one variable is declared in a declaration, care must be taken that the type and initialized value of the variable are handled correctly.


2 Answers

LINT wants a single var declaration statement, but it can be spread over multiple lines.

var a, b, c;

or

var a,
    b,
    c;

The reason it wants a single statement is to avoid any confusion about which variables belong to the local scope. With a single var statement, all locally scoped variables are contained to a single location within the scope and anyone can read the code quickly to see what they are.

It is further recommended that this declaration statement be at the top of the scope, since the JavaScript hoisting mechanism moves them there before execution anyway. By writing your code to expect that statement at the top of the scope, the hoisting mechanism can't cause any unexpected behavior.

like image 66
JAAulde Avatar answered Oct 19 '22 04:10

JAAulde


Neither way is wrong, but I generally prefer to use single line style declarations at the beginning of a code block. The most important thing is to keep it consistent. Example:

function() {
  var foo = "bar",
      number = 123,
      etc = "...";

  // stuff..
}
like image 34
jdc0589 Avatar answered Oct 19 '22 03:10

jdc0589