function showMessage(text) {
alert(count ?? "unknown");
}
let user = {};
alert(user.address.street); // Error!
// Error if the result of querySelector(...) is null
let html = document.querySelector('.my-element').innerHTML;
✔️ Alternative: &&
operator
let user = {}; // user has no address
alert( user && user.address && user.address.street ); // undefined (no error)
// Access "user.address.street"
let user = {};
alert( user?.address?.street ); // undefined (no error)
// .() Function
let user1 = {
admin() {
alert("I am admin");
}
}
let user2 = {};
user1.admin?.(); // I am admin
user2.admin?.();
// .[] Key
let user1 = {
firstName: "John"
};
let user2 = null;
let key = "firstName";
alert( user1?.[key] ); // John
alert( user2?.[key] ); // undefined
// Delete
delete user?.name; // delete user.name if user exists