Toán tử optional chaining (?.) được giới thiệu trong ES2020, cho phép truy cập thuộc tính lồng nhau mà không cần kiểm tra rõ ràng từng tham chiếu trong chuỗi có phải null hoặc undefined. Trước đây, ta dùng toán tử && để kiểm tra, nhưng giờ có thể dùng ?..
Ví dụ
<!DOCTYPE html> <html lang="vi"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Optional Chaining</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> </head> <body> <h1>Toán tử Optional Chaining trong JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">NHẤN VÀO ĐÂY</button> <h3>Nhấn nút để dùng optional chaining truy cập thuộc tính đối tượng person</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let person = { name: "Rohan", location: { state: "Delhi", country: "India" }, }; BtnEle.addEventListener("click", () => { resEle.innerHTML = "person?.location?.state = " + person?.location?.state + "<br>"; resEle.innerHTML += "person?.location?.country = " + person?.location?.country + "<br>"; resEle.innerHTML += "person?.personalDetails?.birthDate = " + person?.personalDetails?.birthDate + "<br>"; }); </script> </body> </html>
Kết quả
Khi nhấn nút:
- person?.location?.state = Delhi
- person?.location?.country = India
- person?.personalDetails?.birthDate = undefined (vì personalDetails không tồn tại)
Toán tử ?. ngăn chặn lỗi TypeError khi truy cập thuộc tính của null/undefined, trả về undefined thay vì ném lỗi. Cũng có thể dùng với gọi hàm: obj.method?.() và truy cập mảng: arr?.[0].