JavaScript ES2020 hỗ trợ toán tử nullish coalescing ?? - chỉ fallback khi giá trị là null hoặc undefined (khác với || fallback cho tất cả falsy).
Cú pháp
var value = null;
var result = value ?? "Giá trị mặc định";
Ví dụ so sánh || vs ??
var fullName = null;
console.log("Giá trị null:", fullName);
var withOR = fullName || "David Miller"; // Dùng ||
var withNullish = fullName ?? "David Miller"; // Dùng ??
console.log("Với ||:", withOR);
console.log("Với ??:", withNullish);
// Trường hợp khác biệt
var emptyString = "";
console.log("Empty string ||:", emptyString || "DEFAULT"); // "DEFAULT"
console.log("Empty string ??:", emptyString ?? "DEFAULT"); // "" (giữ nguyên)
Cách chạy
node demo.js
Kết quả
Giá trị null: null
Với ||: David Miller
Với ???: David Miller
Empty string ||: DEFAULT
Empty string ???:
Khuyên dùng: ?? an toàn hơn khi 0, "", false là giá trị hợp lệ.