Skip to main content

Type Casting & Naming Conventions

Type Casting & Coercion​

Ép kiểu thực hiện ở đầu câu lệnh​

String: dùng String(), không dùng new String() hay + ''​

// ✅ Tốt
const totalScore = String(this.reviewScore);

Number: dùng Number(); parseInt luôn truyền radix (thường là 10)​

// ✅ Tốt
const val = Number(inputValue);
const val = parseInt(inputValue, 10);

Boolean: dùng Boolean() hoặc !!​

// ✅ Tốt
const hasAge = Boolean(age);
const hasAge = !!age;

Naming Conventions​

Tránh tên một chữ; đặt tên có ý nghĩa​

// ✅ Tốt
function query() {}

Object, function, instance: camelCase​

// ✅ Tốt
const thisIsMyObject = {};
function thisIsMyFunction() {}

Constructor / Class: PascalCase​

// ✅ Tốt
class User {
constructor(options) {
this.name = options.name;
}
}
const good = new User({ name: "yup" });

Không dùng leading/trailing underscore​

Leading underscore thường hiểu là “private” nhưng vẫn là public; tránh gây hiểu nhầm.

Không lưu reference this vào self/that; dùng arrow function hoặc Function#bind​

Tên file default export nên khớp với tên export​

// ✅ Tốt: file CheckBox.js
class CheckBox {}
export default CheckBox;
// ✅ Tốt: import
import CheckBox from "./CheckBox";

Export default là function: tên file camelCase trùng tên hàm​

Export constructor/class/singleton/library: PascalCase​

Viết tắt (acronym): hoặc toàn UPPER hoặc toàn lower​

// ✅ Tốt
import SMSContainer from "./containers/SMSContainer";
const httpRequests = [];
// best: tránh viết tắt khi có thể
import TextMessageContainer from "./containers/TextMessageContainer";

Hằng số (export, const, không đổi): có thể UPPER_CASE​

Chỉ dùng cho constant thực sự; không uppercase mọi const trong file.

// ✅ Tốt
export const API_KEY = "SOMEKEY";
export const MAPPING = { key: "value" };