javascript code guideline

2020-09-27  本文已影响0人  芒鞋儿
1.

if (!object[propertyName]) => if (object[propertyName] === undefined)

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

上一篇 下一篇

猜你喜欢

热点阅读