I use it. If you don't, read these:
You can still ignore semicolons, but know that ASI is a syntactic error correction procedure, according to Brendan Eich himself.
- Never mix tabs or spaces.
- Prefer spaces over hard tabs for indentation (I recommend 2 spaces).
- Eliminate end of line whitespace.
- Eliminate blank line whitespace.
- Too much space and no space at all are equally bad.
- Use
camelCase
for variables. - Contructor functions must start with capital letter like
ModalWindow
. - Avoid names like
handler
,data
, or other generic words. - Don't even think about using Hungarian notation.
Choose between single or double quotes, but don't mix different quote types in the same project.
// Add whitespace around parens and braces,
// but not around arguments.
if (something) {
doSomething();
}
if (something) {
doSomething();
} else {
doSomethingElse();
}
// Again, no spaces around arguments.
while (condition) {
doSomething();
}
// The whitespace balance.
for (var i = 0; i < 100; i++) {
doSomething();
}
// Variables
var name = "John Doe"
, email = "[email protected]"
, status
;
// Literal notation
var array = []
, object = {}
;
// Object attributes
var object = {
name: "John Doe"
, email: "[email protected]"
, status: null
};
// Named and assigned functions
function hello() {
doSomething();
}
var hello = function() {
doSomething();
};
// Argument declaration
function hello(message, name, callback) {
doSomething();
}
// Executing functions
// -------------------
//
// Callbacks must ignore spaces around parens and braces
hello("Hi there", "John Doe", function(){
doSomethingElse();
});
Use ===
and !==
wherever is possible.
function something(arg) {
var result;
if (!arg) {
return;
}
result = doSomething();
result = doSomethingElse(result);
return result;
}
Don't use ifs to return a boolean. So instead of doing
function greater(a, b) {
if (a > b) {
return true;
} else {
return false;
}
}
return the expression itself.
function greater(a, b) {
return a > b;
}