Serials Javascript Style Guide – Blocks
Blocks
16.1 Braces
Luôn sử dụng dấu ngoặc nhọn {} với khối có nhiều dòng. eslint: nonblock-statement-body-position
// bad
if (test)
  return false;
// good
if (test) return false;
// good
if (test) {
  return false;
}
// bad
function foo() { return false; }
// good
function bar() {
  return false;
}
16.2 Cuddled elses
Nếu bạn sử dụng khối có nhiều dòng với lệnh if và else, thì đặt else cùng dòng với dấu ngoặc nhọn đóng của khối if. eslint: brace-style
// bad
if (test) {
  thing1();
  thing2();
}
else {
  thing3();
}
// good
if (test) {
  thing1();
  thing2();
} else {
  thing3();
}
16.3 No else return
Nếu khối if luôn chạy lệnh return, thì khối else là không cần thiết. Nếu trong khối else if có return thì nên tách nhỏ ra làm nhiều khối if có chứa return. eslint: no-else-return
// bad
function foo() {
  if (x) {
    return x;
  } else {
    return y;
  }
}
// bad
function cats() {
  if (x) {
    return x;
  } else if (y) {
    return y;
  }
}
// bad
function dogs() {
  if (x) {
    return x;
  } else {
    if (y) {
      return y;
    }
  }
}
// good
function foo() {
  if (x) {
    return x;
  }
  return y;
}
// good
function cats() {
  if (x) {
    return x;
  }
  if (y) {
    return y;
  }
}
// good
function dogs(x) {
  if (x) {
    if (z) {
      return y;
    }
  } else {
    return z;
  }
}