Optional Chaining với Nullish Coalescing
Xuất bản ngày
javascripttil
Optional Chaining với Nullish Coalescing
Hôm nay tôi học được cách kết hợp optional chaining (?.) và nullish coalescing (??) có thể mạnh mẽ như thế nào.
Pattern
const value = obj?.property?.nested ?? 'default';Điều này truy cập an toàn các thuộc tính lồng nhau và cung cấp giá trị mặc định nếu kết quả là null hoặc undefined.
Ví dụ
const user = {
profile: {
name: 'John'
}
};
// Cách cũ
const email = user && user.profile && user.profile.email
? user.profile.email
: 'no-email@example.com';
// Cách mới
const email = user?.profile?.email ?? 'no-email@example.com';Sạch hơn nhiều!