JavaScript

JS Coding Convention

Quy ước viết code JavaScript/TypeScript hiện đại — tổng hợp từ Airbnb & Google style.

Naming

  • camelCase cho biến và hàm: userName, getUser()
  • PascalCase cho class & component: UserCard
  • UPPER_SNAKE cho hằng: MAX_RETRIES
  • Boolean prefix: is, has, canisLoading
  • Tránh viết tắt: btn ❌ → button

Variable & types

💡Ưu tiên const, dùng let khi cần re-assign. KHÔNG dùng var.
ts
const items: Item[] = []; // immutable reference let count = 0; // re-assign // var ❌

Function

  • Hàm thuần (pure) khi có thể — không side effect.
  • Tham số ≤ 3. Nhiều hơn → đóng gói thành object.
  • Early return thay cho nested if.
js
// ❌ function f(user) { if (user) { if (user.active) { return doSomething(user); } } } // ✅ function f(user) { if (!user || !user.active) return; return doSomething(user); }

Object & array

js
// Spread thay Object.assign const merged = { ...a, ...b }; // Destructure khi đọc const { name, age } = user; // Trailing comma cho diff dễ đọc const arr = [ 'a', 'b', 'c', ];

Async

  • Dùng async/await thay cho .then() chained dài.
  • Promise.all để chạy song song độc lập.
  • Luôn try/catch boundary, tối thiểu 1 nơi.

Linter & formatter

Thiết lập ESLint (extends next/core-web-vitals) + Prettier. Không tranh cãi style trong PR — để máy quyết.

Google JavaScript Style Guide