I'm looking at Douglas Crockford's Code Conventions for JavaScript document, and he's saying that var
s 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?
We can also declare two variables and copy data from one into the other.
Java static code analysis | convention: Multiple variables should not be declared on the same line.
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.
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.
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..
}
If 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