Optional chaining is a feature introduced in ECMAScript 2020 (ES11) that allows you to access nested properties of an object without the need to explicitly check if each level of the nested property exists. It helps to avoid errors when trying to access properties of an object that may be undefined or null along the chain.
// Sample object
const user = {
name: 'John',
address: {
city: 'New York',
postalCode: '10001'
}
};
// Accessing nested property without optional chaining
const cityWithoutOptionalChaining = user.address.city; // 'New York'
// Accessing nested property with optional chaining
const cityWithOptionalChaining = user.address?.city; // 'New York'
// Accessing nested property that does not exist without optional chaining
const streetWithoutOptionalChaining = user.address.street; // undefined
// Accessing nested property that does not exist with optional chaining
const streetWithOptionalChaining = user.address?.street; // undefined
cityWithoutOptionalChainingaccesses thecityproperty of theaddressobject without optional chaining, which works fine sinceuser.addressexists.
cityWithOptionalChainingaccesses thecityproperty of theaddressobject using optional chaining (?.). Ifuser.addresswere undefined or null, it would return undefined instead of throwing an error.
streetWithoutOptionalChainingattempts to access the non-existentstreetproperty of theaddressobject without optional chaining, which results in undefined.
streetWithOptionalChainingattempts to access the non-existentstreetproperty of theaddressobject using optional chaining, which also results in undefined without throwing an error.