Reserved Words (Từ khóa dành riêng) là các từ không thể dùng làm tên biến, hàm, tham số, property (trong strict mode), nhãn vòng lặp, v.v. Chúng dành cho cú pháp ngôn ngữ hiện tại hoặc tương lai.
Phân loại Reserved Words
1. Keywords (Đang sử dụng - Keywords hiện hành)
Có chức năng cú pháp hiện tại. Không dùng làm identifier được.
break, case, catch, class, const, continue, debugger, default, delete, do,
else, export, extends, false, finally, for, function, if, import, in,
instanceof, new, null, return, super, switch, this, throw, true, try,
typeof, var, void, while, with, yield, let, static, await*
await là keyword trong module/async function (ES2017).
2. Future Reserved Words (Dành cho tương lai)
Dự trữ cho các phiên bản sau. Trong strict mode bị cấm dùng làm identifier. Non-strict mode có thể dùng (nhưng KHÔNG NÊN).
enum, implements, interface, package, private, protected, public
3. Legacy Reserved Words (Dành riêng cũ - ES5 strict mode)
Chỉ cấm trong strict mode.
arguments, eval
4. Literals (Chuẩn bị cho literal)
null, true, false
Bảng đầy đủ (theo ECMAScript 2024)
| Nhóm | Từ khóa |
|---|---|
| Control flow | break, case, catch, continue, default, do, else, finally, for, if, return, switch, throw, try, while, with |
| Declaration | class, const, export, function, import, let, var |
| Async/Generator | await, yield |
| OOP/Module | extends, super, implements, interface, package, private, protected, public, static, enum |
| Literal/Primitive | null, true, false |
| Meta | debugger, typeof, instanceof, void, delete, new, in, this |
| Strict-only | arguments, eval |
Các từ KHÔNG phải reserved (có thể dùng làm tên biến)
// Các từ thường bị nhầm là reserved nhưng KHÔNG:
undefined, NaN, Infinity, eval, arguments, constructor, prototype,
toString, valueOf, hasOwnProperty, isPrototypeOf, propertyIsEnumerable,
console, document, window, global, require, module, exports, define,
Promise, Map, Set, Symbol, Proxy, Reflect, Array, Object, Function,
String, Number, Boolean, Date, RegExp, Error, JSON, Math
Tuy nhiên, ghi đè chúng (shadowing) là thực hành xấu – tránh dùng.
Kiểm tra identifier hợp lệ
// Regex kiểm tra tên biến hợp lệ (Unicode aware)
function isValidIdentifier(str) {
try {
new Function(`var ${str} = 1;`);
return true;
} catch {
return false;
}
}
console.log(isValidIdentifier("class")); // false
console.log(isValidIdentifier("myClass")); // true
console.log(isValidIdentifier("undefined")); // true (nhưng không nên)
console.log(isValidIdentifier("await")); // false (trong module)
Lưu ý quan trọng
- Property accessor (
obj.class,obj["class"]) KHÔNG bị cấm – chỉ identifier đơn độc bị cấm. - Strict mode cấm nhiều từ hơn non-strict.
- ES Modules (type="module") mặc định strict mode.
- Dùng ESLint rule
no-restricted-syntaxhoặcid-denylistđể cấm shadowing built-ins.