Đặt tên biến tốt làm code dễ đọc, bảo trì, giảm bug. JavaScript có quy tắc bắt buộc (syntax) và quy ước cộng đồng (convention).
Quy tắc BẮT BUỘC (Syntax Rules)
| Quy tắc | Hợp lệ | Không hợp lệ |
| Ký tự đầu | Chữ cái (a-z, A-Z), _, $ | Số (0-9) |
| Ký tự sau | Chữ cái, số, _, $ | Khoảng trắng, dấu gạch ngang, ký tự đặc biệt |
| Phân biệt hoa/thường | name ≠ Name ≠ NAME | - |
| Không dùng reserved words | myClass, _default | class, function, var, let... |
| Unicode | Hỗ trợ Unicode: 变量, 変数, 변수 | - |
Quy ước CỘNG ĐỒNG (Best Practices)
1. camelCase – Biến, hàm, tham số, property (Chuẩn JS)
let userName = "An";
const maxRetryCount = 3;
function getUserById(id) { ... }
obj.userName = "Binh";
2. PascalCase – Class, Constructor, Component (React), Type
class UserAccount { ... }
function UserProfile() { ... }
const MyComponent = () => ;
type UserData = { name: string };
3. UPPER_SNAKE_CASE – Hằng số toàn cục (Constants)
const API_BASE_URL = "https://api.example.com";
const MAX_FILE_SIZE_MB = 10;
const DEFAULT_TIMEOUT_MS = 5000;
4. _prefix – Private/Internal (Convention)
class User {
#privateField = "true private"; // ES2022 true private
_internalCache = {}; // Convention: internal use
publicMethod() { ... }
}
5. Boolean prefix – is/has/can/should
let isActive = true;
let hasPermission = false;
let canEdit = true;
let shouldRetry = false;
6. Tên mô tả ý nghĩa (Semantic naming)
| Kém | Tốt | Lý do |
x, data, temp | userCount, productList, tempFilePath | Ý nghĩa rõ ràng |
getData() | fetchUserList() | Hành động + đối tượng |
flag | isLoading | Boolean prefix |
arr | userNames | Chỉ rõ nội dung |
Ví dụ tổng hợp
// Constants
const DEFAULT_PAGE_SIZE = 20;
const API_ENDPOINTS = {
USERS: "/api/users",
POSTS: "/api/posts"
};
// Variables
let currentUser = null;
let isLoading = false;
let userList = [];
// Functions
async function fetchUserList(page = 1) {
isLoading = true;
try {
const response = await fetch(`${API_ENDPOINTS.USERS}?page=${page}&limit=${DEFAULT_PAGE_SIZE}`);
const data = await response.json();
userList = data.users;
return userList;
} finally {
isLoading = false;
}
}
// Class
class UserService {
#cache = new Map(); // True private (ES2022)
async getUser(id) {
if (this.#cache.has(id)) return this.#cache.get(id);
const user = await fetch(`/api/users/${id}`).then(r => r.json());
this.#cache.set(id, user);
return user;
}
}
Công cụ hỗ trợ
- ESLint: rule
camelcase, id-denylist, id-match.
- Prettier: Format tự động (không check naming).
- TypeScript: Type annotation giúp tên biến rõ ngữ cảnh.
Tóm tắt
- Bắt buộc: Không bắt đầu bằng số, không dùng reserved word, phân biệt hoa/thường.
- Khuyến nghị: camelCase (biến/hàm), PascalCase (Class), UPPER_SNAKE_CASE (const global), prefix
_ (private), prefix is/has/can (boolean).
- Đặt tên có ý nghĩa, tránh viết tắt غامض, nhất quán trong codebase.