1.
if (!object[propertyName]) => if (object[propertyName] === undefined)
-
use === instead of ==
"==" is loose operator -
Addition operators: operand 1 + operand 2
operand 1 and operand 2 should be the same data type,
both are numbers or both strings -
if(condition) {...}
while (condition) {...}
condition should be boolean
2.
array.indexOf(item) != -1 => array.includes(item)
js => ES2015
3.
use let to limit the variables life as much as possible.
eg. index and item are only used in for block scope, so limit them in the for loop block.
function someFunc(array) {
/*
* Lots of code
*/
const length = array.length;
for (let index = 0; index < length; index++) {
const item = array[index];
// Use `item`
}
return someResult;
}
Also, limit the variables in if block scope,
// Bad
let message;
// ...
if (notFound) {
message = 'Item not found';
// Use `message`
}
// Good
if (notFound) {
const message = 'Item not found';
// Use `message`
}
4.
Variables, object properties, arrays must be initialized with values before using them!
// Bad
function foo(options) {
if (object.optionalProp1 === undefined) {
object.optionalProp1 = 'Default value 1';
}
// ...
}
// Good
function foo(options) {
const defaultProps = {
optionalProp1: 'Default value 1'
};
options = {
...defaultProps,
...options
};
// ...
}
// Bad
function foo(param1, param2) {
if (param2 === undefined) {
param2 = 'Some default value';
}
// ...
}
// Good
function foo(param1, param2 = 'Some default value') {
// ...
}
null is indicator of a missing project.
You should strive to avoid returning null from functions, and more importantly, call functions with null as an argument.
As soon as null appears in your call stack, you have to check for its existence in every function that potentially can access null. It’s error-prone.
5.
use eslint
Ref:
https://dmitripavlutin.com/unlearn-javascript-bad-coding-habits/
Very referable guideline:
airbnb code guideline
google code guideline
网友评论