1. Do not contaminate function scope
if block scope
// 不好
let message;
// ...
if (notFound) {
message = 'Item not found';
// Use `message`
}
// 好
if (notFound) {
const message = 'Item not found';
// Use `message`
}
for block scope
// 不好
let item;
for (item of array) {
// Use `item`
}
// 好
for (const item of array) {
// Use `item`
}
}
2. Try to avoid undefined and null
Determine whether there is property
// 不好
const object = {
prop: 'value'
};
if (object.nonExistingProp === undefined) {
// ...
}
// 好
const object = {
prop: 'value'
};
if ('nonExistingProp' in object) {
// ...
}
The default property of the object
// 不好
function foo(options) {
if (object.optionalProp1 === undefined) {
object.optionalProp1 = 'Default value 1';
}
// ...
}
// 好
function foo(options) {
const defaultProps = {
optionalProp1: 'Default value 1'
};
options = {
...defaultProps,
...options
}
}
The default function arguments
// 不好
function foo(param1, param2) {
if (param2 === undefined) {
param2 = 'Some default value';
}
// ...
}
// 好
function foo(param1, param2 = 'Some default value') {
// ...
}
3. Do not use implicit type conversion