- Terminate all statements with a semicolon
;
- Curly braces should open on the same line and close on a new line
// function declaration
function myFunction (<parameters>) {
...
}
// if-else
if (<predicate>) {
...
} else if {
...
} else {
...
}
- Always use curly braces. (Even if the code block is only one statement.)
- This prevents errors when adding new lines of code to blocks.
// right
if (<predicate>) {
return true;
} else {
return false;
}
// wrong
if (<predicate>)
return true;
else
return false
// worse
if (<predicate>) return true;
else return false
- Leaving a single space between the
if
statement and the first parenthesis
if (<predicate>) {
...
} else if (<predicate>) {
...
}
- When calling a function with multiple parameters, leave a space after each comma
- clean up all trailing whitespace before submitting you code.
function myFunction(arg1, arg2, arg3){
...
};
myfunction(1, 2, 3);
- When naming variables use lower camel case. eg. myVariable, x, johnDoe
- Declare one variable per var statement.
- It makes it easier to re-order the lines.
- Do not use the comma operator
//right
var x = 1;
var y = 2;
//wrong
var x = 1,
y = 2;