1.不要污染函数作用域
if 块作用域
// 不好
let message;
// ...
if (notFound) {
message = 'Item not found';
// Use `message`
}
// 好
if (notFound) {
const message = 'Item not found';
// Use `message`
}
for 块作用域
// 不好
let item;
for (item of array) {
// Use `item`
}
// 好
for (const item of array) {
// Use `item`
}
}
2.尽量避免 undefined 和 null
判断属性是否存在
// 不好
const object = {
prop: 'value'
};
if (object.nonExistingProp === undefined) {
// ...
}
// 好
const object = {
prop: 'value'
};
if ('nonExistingProp' in 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
}
}
默认函数参数
// 不好
function foo(param1, param2) {
if (param2 === undefined) {
param2 = 'Some default value';
}
// ...
}
// 好
function foo(param1, param2 = 'Some default value') {
// ...
}
3.不要使用隐式类型转换