JavaScript Style Guide

·

3 min read

In JavaScript, we usually use camelCase for naming variables, functions, and object properties, but for naming classes, we use PascalCase. This helps to differentiate between classes and regular variables and makes the code more readable and easier to understand.

Variables

Always use meaningful nouns to make the variable clear.

// bad
let setCount = 10;

// good
let maxCount = 10;

Constant

Always use all-caps snake case to name a constant.

// bad
const serverErrorCode = {
  success: 200,
  internalServerError: 500,
};

// good
const SERVER_ERROR_CODE = {
  SUCCESS: 200,
  INTERNAL_SERVER_ERROR: 500,
};

Function / Method

Always use a combination of verbs and nouns.

// bad
function essay() {}

// good
function writeEssay() {}

Most Used: get, set, load, is, has

Classes

As mentioned above, using PascalCase to name classes helps differentiate between classes and regular variables.

// bad
class human {}
class exampleClass {}

// good
class Human {}
class ExampleClass {}

Comments

Single Line

// Single line comment
let total = 10;

// multiple line comment

/**
 * let min = 10;
 * let max = 100;
 * let avg = 50;
 * /

Reduce nesting

When the conditions are not allowed, return as soon as possible to improve your code readability.

// bad
if (condition1) {
    if (condition2) {
        ...
    }
}

// good
if (!condition1) return
if (!condition2) return
...

Reduce unclear variables

Use constants as explanations instead of using comments.

// bad
// 1:add  2:edit  3:delete
type: 1 | 2 | 3;

// good
const MODIFY_TYPE = {
  ADD: 1,
  EDIT: 2,
  DELETE: 3,
} as const;

type: MODIFY_TYPE.ADD;

Expression

Keep your expression as simple as possible.

// bad
if (name === '') {
}
if (collection.length > 0) {
}
if (notTrue === false) {
}

// good
if (!name) {
}
if (collection.length) {
}
if (notTrue) {
}

Use positive phrasing

Use positive words to express the situation. Negative words make it difficult to understand when making negative judgments.

// bad
if (!isProductNotReleased) {
}

// good
if (isProductReleased) {
}

if (!isProductReleased) {
}

Handling branches

For multiple value conditions on the same variable or expression, use switch instead of if.

// bad
let type = typeof variable;
if (type === 'object') {
  // ......
} else if (type === 'number' || type === 'boolean' || type === 'string') {
  // ......
}

// good
switch (typeof variable) {
  case 'object':
    // ......
    break;
  case 'number':
  case 'boolean':
  case 'string':
    // ......
    break;
}

Use variable names for explanation

When the logic is complex, it is recommended to define new variables to clarify the expression, instead of using cryptic shorthand.

// bad
function isQualifiedPlayer(user) {
  return (
    (user.rate > 80 && user.score > 300 && user.level > 120) ||
    user.medals.filter(medal => medal.type === 'gold').length > 10
  );
}

// good
function isQualifiedPlayer(value) {
  const isExperiencedPlayer = user.rate > 80 && user.score > 300 && user.level > 120;
  const isGoldMedalPlayer = user.medals.filter(medal => medal.type === 'gold').length > 10;
  return isExperiencedPlayer || isGoldMedalPlayer;
}

Use function names for explanation

Adhere to the principle of single responsibility, logic can be hidden in functions, while using accurate function names to explain.

// bad
if (modifyType === MODIFY_TYPE.ADD) {
    await batchVariableAPI(data);
    this.closeModal();
    this.$toast.show('Insert success!');
} else {
    await updateVariableAPI(data);
    this.closeModal();
    this.$toast.show('Edit success!');
}

// good
modifyType === MODIFY_TYPE.ADD ? this._insertVariable(data) : this._updateVariable(data);

async _insertVariable(data) {
    await batchVariableAPI(data);
    this._successOperation('Insert success!');
}

async _updateVariable(data) {
    await updateVariableAPI(data);
    this._successOperation('Edit success!');
}

_successOperation(toastMsg) {
    this.closeModal()
    this.$toast.show(toastMsg)
}

Did you find this article valuable?

Support Shineve's Blog by becoming a sponsor. Any amount is appreciated!