Sự khác biệt cốt lõi: null là từ khóa (keyword) / literal, trong khi undefined là property toàn cục (global property).
Phân tích chi tiết
null - Literal / Reserved Word
- Là literal (giá trị literal) biểu thị "không có giá trị object".
- Là reserved word – không thể dùng làm identifier (tên biến, hàm, property).
var null = 1;→ SyntaxError: Unexpected token 'null'.function null() {}→ SyntaxError.- Trong strict mode: cấm hoàn toàn.
undefined - Global Property
- Là property của global object (
window.undefinedtrong browser,global.undefinedtrong Node). - Giá trị mặc định:
undefined(primitive). - Không phải reserved word – có thể dùng làm tên biến (nhưng KHÔNG NÊN).
var undefined = 1;→ Hợp lệ (trong non-strict mode), tạo biến local che global property.- Trong strict mode:
undefinedlà read-only – gán giá trị báo TypeError (nhưng khai báovar undefinedvẫn được).
Ví dụ minh họa
// Non-strict mode
var undefined = "I changed it!"; // Hợp lệ! Tạo biến local
console.log(undefined); // "I changed it!"
console.log(window.undefined); // undefined (global không đổi)
// Strict mode
"use strict";
var undefined = 1; // Hợp lệ (khai báo var được), nhưng...
undefined = 2; // TypeError: Assignment to read-only property
// var null = 1; // SyntaxError (luôn cấm)
Bảng so sánh
| Đặc điểm | null | undefined |
|---|---|---|
| Phân loại | Literal / Keyword | Global property |
| Dùng làm identifier? | ❌ Không (SyntaxError) | ⚠️ Được (non-strict) / Read-only (strict) |
| typeof | "object" (bug lịch sử) | "undefined" |
| Giá trị boolean | falsy | falsy |
| Ý nghĩa | "Rỗng cố ý" (intentional absence) | "Chưa gán giá trị" (uninitialized) |
| JSON | Hỗ trợ null | Không hỗ trợ (bỏ qua property) |
Tại sao typeof null === "object"?
Bug từ phiên bản đầu tiên của JS (1995). Giá trị null được biểu diễn bằng con trỏ NULL (0x00) – cùng tag với object. Không thể sửa vì breaking change quá lớn.
Best Practice
- Không bao giờ khai báo biến tên
undefined– gây nhầm lẫn cực lớn. - Kiểm tra undefined:
typeof x === "undefined"hoặcx === undefined(nếu chắc chắn biến đã khai báo). - Dùng
nullđể set giá trị "rỗng chủ động",undefinedđể để engine quản lý. - Luôn bật
"use strict"hoặc dùng ES Modules (strict mặc định).