wiki

View on GitHub

Javascript coding convention

File

Object, Array

// bad
users[users.length] = 'new user';

// good
users.push('new user');
const itemsCopy = [...items];

String, Interger, …

function sayHi(name) {
  return `How are you, ${name}?`;
}
const goSportsTeam = true;
const items = getItems();
let dragonball;
let i;
let length;

Đặt tên

function getType() {
  console.log('fetching type...');

  // set the default type to 'no type'
  var type = this.type || 'no type';

  return type;
}

Function

let test;
if (currentUser) {
  test = function test() {
    console.log('Yup.');
  };
}
// good
function handleThings(name, opts = {}) {
  // ...
}

Khoảng trắng

const arr = [[0, 1], [2, 3], [4, 5]];

const objectInArray = [
  {
    id: 1,
  },
  {
    id: 2,
  }
];

const numberInArray = [
  1,
  2
];

Các phép toán

// bad
if (isValid === true) {
  // ...
}

// good
if (isValid) {
  // ...
}

// bad
if (name) {
  // ...
}

// good
if (name !== '') {
  // ...
}

// bad
if (collection.length) {
  // ...
}

// good
if (collection.length > 0) {
  // ...
}