Optional Chaining (But reading this article is not optional…😉)

let user = {}; // a user without "address" propertyalert(user.address.street); // Error!
// document.querySelector('.elem') is null if there's no element let html = document.querySelector('.elem').innerHTML; // error if it's null
let user = {}; // user has no addressalert( user.address && user.address.street && user.address.street.name ); // undefined (no error)
let user = {}; // user has no addressalert( user?.address?.street ); // undefined (no error)
let user = null;alert( user?.address ); // undefined
alert( user?.address.street ); // undefined
// ReferenceError: user is not defined
user?.address;

Other variants: ?.(), ?.[]

let userAdmin = {
admin() {
alert("I am admin");
}
};
let userGuest = {};userAdmin.admin?.(); // I am adminuserGuest.admin?.(); // nothing (no such method)
let person1 = {
firstName: "John"
};
let person2 = null; // Imagine, we couldn't authorize the userlet key = "firstName";alert( person1?.[key] ); // John
alert( person2?.[key] ); // undefined
alert( person1?.[key]?.something?.not?.existing); // undefined
delete person?.name; // delete person.name if person exists
obj.val?.prop
obj.val?.[expr]
obj.arr?.[index]
obj.func?.(args)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store