I. Basic Formatting
- Indentation
It is recommended to use 4 spaces per level. You can set tab = 4 spaces in the editor for automatic conversion.
- Semicolons
Do not omit semicolons to prevent ASI (Automatic Semicolon Insertion) errors.
- Line Width
Each line of code should not exceed 80 characters. If too long, manually break the line using operators.
- Line Breaking
Operators should be at the end of the previous line, and the next line should be indented 2 levels. If it's an assignment statement, it should also align with the part after the equal sign.
- Blank Lines
There should be blank lines between function declarations and function declarations, variable declarations and function declarations, and logical blocks within functions.
Nicholas also recommends leaving a blank line at the top of control flow blocks, but the examples given are not very clear.
-
Naming
-
Variable names/function names: Camel case rules, first word's first letter lowercase, subsequent words' first letters uppercase, rest lowercase
-
Constant names: C language style, all uppercase, underscores to separate words
-
Constructor functions: Pascal rules, all words' first letters uppercase, rest lowercase
-
-
Literals
-
Strings: Wrapped in double quotes, break lines using [+] operator, do not use \ escape characters
-
Numbers: Do not omit parts before or after the decimal point, do not use octal form
-
Null: Only use null as a placeholder for Object, do not use it to detect parameters, and do not use it to detect uninitialized variables
-
Undefined: All objects should be initialized to null to distinguish between undefined and uninitialized
-
Object literals/array literals: Do not use constructor methods to declare objects and arrays
-
II. Comments
P.S. There is a very classic explanation in the book:
Appropriately written comments help tell the story of code, allowing other developers to drop into a part of the story without needing to hear the beginning.
-
Single-line Comments
-
End of line: Separate from code with 1 level of indentation, and there should be a space after //
-
Occupying a line alone: Used to comment below, should have the same indentation as the commented code
-
Beginning of line: Used to comment multiple lines of code
-
-
Multi-line Comments
Used to wrap large blocks of comments. Eclipse style is recommended, for example:
code
/*
* comment line1
* comment line2
*/
Notes:
- Leave a blank line above multi-line comments
- Leave a space after the * asterisk
- Multi-line comments should be at least three lines (because nothing is added after the first and last lines)
3. Where to Add Comments
- Code that cannot self-explain
- Intentional, but looks like it might be wrong
- Browser-specific hacks
4. Documentation Comments
Comments should be added to each function, including function description, parameters, return values, thrown errors, etc. For example, the recommended Eclipse style:
/**
* Add specified element to default array
*
* @method add
* @param {Number} Element to be added
* @return {Boolean} Add success/failure
* @throw {TypeError} Parameter type mismatch
*/
function add(item){
if(typeof item === "number"){
arr.push(item)
}
else{
throw new TypeError();
}
}
III. Statements and Expressions
- Curly Brace Alignment Style
End-of-line style is recommended, next-line style is not recommended
- Block Statement Spaces
There should be a space before and after the parentheses following if, for example:
if (expr) {
code
}
3. switch Statements
- Indentation: case aligns with switch, break indented 1 level
- Case fall-through: Use blank lines or comment //falls through to indicate case fall-through is intentional
- default: Keep default or use comment //no default to indicate no default
P.S. Douglas, author of "JavaScript: The Good Parts", believes case fall-through should not be used (calls it useless) because it easily causes bugs, while Nicholas believes using blank lines or comments to explain is fine
- with Statements
Do not use
- for Loops
All variables should be declared at the top of the function body, including variables used in the for loop initialization part, to avoid hosting (hoisting) causing bugs (may shadow global variables)
- for-in Loops
Do not use to iterate over arrays. Remember to add hasOwnProperty filter when using. If intentionally iterating over prototype properties, should explain with comments
IV. Variables, Functions, Operators
- Variable Declarations
Function body = variable declarations + function declarations + logical statements. Separate each part with blank lines
- Function Declarations
Declare before use. Never put function declarations inside if branches, because browsers understand differently, and ES doesn't provide a standard
- Function Calls
No spaces before or after parentheses to avoid confusion with block statements
- Anonymous Function Immediately Invoked
Wrap immediately executed anonymous functions in parentheses to avoid confusion with anonymous function declarations
- Strict Mode
Do not enable strict mode in global scope, only enable inside functions. To enable for multiple functions, use immediately invoked anonymous function to limit the scope of strict mode
- Equality Comparison
Only use === and !==
- eval
Do not use eval() and new Function(). Use anonymous functions to optimize setTimeout() and setInterval()
- Primitive Wrapper Types
Do not use new Boolean(), new String(), new Number()
V. Well-Styled Example Code
var obj = { // Note the indentation alignment of object literals
attr1: 1, // Note spaces before and after colon and blank line before this line
attr2: (function() {
// Note special parentheses position of IIFE, not (function(){})()
}()),
_privateAttr: 2, // Private attribute names start with underscore
doSomething: function(arg) { // Method names start with verb and don't use underscore
// Note space usage and line breaking in if-else if-else
if (arg === 1) {
} else if (arg === 2) {
} else {
}
}
}
function Fun() { // Constructor names start with non-verb, Pascal rules (note 2 spaces on this line)
// Multiple variables should be declared together, note equal sign alignment (leave a blank line before comments)
var count = 10, // Variable names start with noun, avoid confusion with fun, and don't use underscore
isTrue = (2 > 1), // Add parentheses around the whole right side when there's comparison operation
color = 0xcccccc; // Can use decimal and hexadecimal, don't use octal, e.g., 011
/**
* Comment methods should use this documentation comment form, use @param etc.
* Multi-line comments should have * at the beginning of each line, align carefully
* All comments (except end-of-line single-line comments) should have a blank line before them
*/
function fun(arg1, arg2) { // Note 3 spaces on this line (function declaration and variable declaration separated by one blank line)
var arr = [1, 2, 3], // Declare properties with default values first
i, // Variables used in loop (including for-in) initialization part should also be declared in advance
len; // Declare properties without default values later
for (i = 0, len = arr.length; i < len; i++) {
// Note space usage in for structure
}
for (i in arr) {
// TODO: Annotation, indicates unfinished task
// HACK: Annotation, indicates browser-specific hack
// XXX: Annotation, indicates very urgent error
// FIXME: Annotation, indicates less urgent error
// REVIEW: Annotation, indicates there may be better implementation
}
while (i < len) {
switch (i) {
case 1:
/* falls through */
case 2:
break;
default:
break;
// Or
// no default
}
}
do {
// Blank line before all statement blocks, use // not /**/ to comment code blocks, latter is used to indicate comment blocks
// try {
// //
// } catch (err) {
// //
// } finally {
// //
// }
} while (i < len); // Note spaces before and after while
return (len > 1 ? true : false); // Add parentheses around whole return value when it's a complex expression
}
}
References
-
"Maintainable JavaScript"
-
"JavaScript: The Good Parts"
No comments yet. Be the first to share your thoughts.