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?
LINT wants a single
vardeclaration statement, but it can be spread over multiple lines.or
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.