Naming conventions
1. Avoid single-letter names. Use your name to describe the feature (preferably with a verb).
Use camelCase when naming objects, functions, and instances.
Use PASCAL naming only when naming constructors or classes. (PascalCase capitalizes the first letter of each word)
class User {
constructor(options) {
this.name = options.name;
}
}
const good = new User({
name: 'yup',
});
Copy the code
4. Do not use leading or trailing underscores.
5. The file name should match the default export name.
You should use PASCAL nomenclature when exporting a constructor/class/singleton/library/exposed object.
7. Abbreviations and abbreviations must be all uppercase or all lowercase.
variable
1. Use const or let to define variables. Avoid polluting the global namespace. (Preferably named with a noun) put together const declarations and let declarations. This is useful later if you need to specify a variable based on the preceding assignment variable.
2. Use definition variables where you need them, but keep them in a reasonable place. Let and const are block-level scoped, not function scoped.
3. Do not chain variable assignments. Chained variable assignments create implicit global variables.
(function example() { let a = 1; let b = a; let c = a; } ()); console.log(a); // throws ReferenceError console.log(b); // throws ReferenceError console.log(c); Throws ReferenceError // Same for constCopy the code
annotation
1, use /**… */ for multi-line comments.
2. Single-line comment with //. Place a single-line comment on a new line above the line you want to comment on. Place a blank line before the comment unless it is on the first line of the block.
The blank space
1. Use tabs to set to 2 Spaces.
2. Place a space before the body.
3. Place a space before the parentheses of control statements (if, while, etc.). In function calls and declarations, there is no space between the argument list and the function name.
4. Separate operators with Spaces.
5. Leave a blank line before the block and the next statement.
6. Don’t add Spaces in parentheses.
7. Do not add Spaces in brackets.
8. Add a space inside the curly braces. const foo = { clark: ‘kent’ };
9. Require open block flags to have the same spacing as the flags on the same line. This rule also enforces a consistent spacing between closed block markers and preceding markers on the same line.
10. Avoid using Spaces before commas. Use Spaces after commas.
11. Avoid Spaces at the end of lines.
A semicolon
Each line ends with a semicolon
methods
Use named function expressions instead of function declarations. The function declaration is suspended, which means it is easy to refer to the function until it is defined in a file. This impairs readability and maintainability. // The term name distinguished from the variable reference call
const short = function longUniqueMoreDescriptiveLexicalFoo() {
// ...
};
Copy the code
Wrap immediately calls the function expression. Immediately called function expressions are single unit-wrapped, and have parentheses called, within parentheses, clear expressions.
(function () { console.log('Welcome to the Internet. Please follow me.'); } ());Copy the code
3. Never declare functions (if, while, etc.) in non-function blocks. Assign a function to a variable.
4. Avoid the side effects of using default parameters. They are easily confused.
5. Always put default parameters last.
6. Spacing in function signatures. Consistency is good, and you don’t need to add or remove Spaces when deleting or adding names.
7. Use extension operators in preference… It’s much cleaner, you don’t have to provide context.
Arrow function
1. Use arrow functions when you must use anonymous functions (when passing inline functions). It creates a version of the function that executes in the this context, which is usually what you want, and has a cleaner syntax. If you have a fairly complex function, you can transfer this logic to its own named function expression.
[1, 2, 3].map((x) => {
const y = x + 1;
return x * y;
});
Copy the code
2. If an expression spans more than one line, enclose it in parentheses for better readability. It clearly shows the start and end of the function.
['get', 'post', 'put'].map(httpMethod => (
Object.prototype.hasOwnProperty.call(
httpMagicObjectWithAVeryLongName,
httpMethod,
)
));
Copy the code
3. If your function accepts an argument, omit the parentheses. Otherwise, parentheses are required around the parameters for clarity and consistency. Note: it is acceptable to always use parentheses, in which case we use “always” option to configure to reduce visual clutter.
4. Avoid confusion between arrow function symbols (=>) and comparison operators (<=, >=).
5. Note the position of the body of the arrow function with an implicit return.
(foo) => bar;
(foo) => (bar);
(foo) => (
bar
)
Copy the code
Class and constructor
Prototype. Class syntax is simpler and easier to reason about.
class Queue { constructor(contents = []) { this.queue = [...contents]; } pop() { const value = this.queue[0]; this.queue.splice(0, 1); return value; }}Copy the code
2. Use extends to extend inheritance. It is a built-in method for inheriting prototype functionality without breaking Instanceof.
class PeekableQueue extends Queue { peek() { return this.queue[0]; }}Copy the code
3. The method returns this for its internal method call.
class Jedi {
jump() {
this.jumping = true;
return this;
}
setHeight(height) {
this.height = height;
return this;
}
}
const luke = new Jedi();
luke.jump()
.setHeight(20);
Copy the code
4. If no class is specified, the class has a default constructor. An empty constructor or a function representing a parent class is not necessary.
class Rey extends Jedi { constructor(... args) { super(... args); this.name = 'Rey'; }}Copy the code
5. Avoid defining duplicate class members. Duplicate class member declarations will default to the last one – having duplicate class members is an error.
class Foo { bar() { return 1; } } class Foo { bar() { return 2; }}Copy the code
Compare operator and equal sign
1. Use === and! == instead of == and! =.
2. Conditional statements, such as if statements, use ToBoolean’s abstract method to evaluate the result of expressions and always follow the following simple rules: Objects: true; Undefined: false; Null: The values of false Booleans are: Boolean values of Numbers: +0, -0, or NaN: false Otherwise, true Strings: False if it is an empty string otherwise true
3. Use abbreviations for booleans, but explicitly compare strings and numbers.
4. For more information check out Angus Croll’s Truth Equality and JavaScript.
5. In case and default clauses, use curly braces to create blocks if there are declarations (e.g. Let, const, function, and class).
6. Ternary expressions should not be nested and are usually single-line expressions.
7. Avoid unnecessary ternary expressions.
8. When using the mixed operator, use parentheses. The only exceptions are the standard arithmetic operators (+, -, *, & /) because their precedence is widely understood. This improves readability and indicates the intent of the developer.
const foo = (a && b < 0) || c > 0 || (d + 1 === 0);
const bar = (a ** b) - (5 % d);
if (a || (b && c)) {
return d;
}
const bar = a + b / c * d;
Copy the code
The code block
1, When there are multiple lines of code blocks, use curly braces.
2. If you are using multi-line blocks of if and else, place the else statement on the same line as the if block closing parentheses.
3. If an if block always executes a return statement, then the following else block is unnecessary. If an else if block containing a return statement is followed by an if block containing a return statement, it can be split into multiple if blocks.
function cats() { if (x) { return x; } if (y) { return y; } } function dogs(x) { if (x) { if (z) { return y; } } else { return z; }}Copy the code