Safely access nested object properties without throwing errors using the optional chaining operator.
Explanation
obj?.prop
: Returnsundefined
ifobj
isnull
orundefined
, otherwise returnsobj.prop
.obj?.method?.()
: Safely calls a method only if it exists.obj?.[key]
: Safely accesses dynamic properties using bracket notation.
Usage
To safely access nested properties, use the optional chaining operator:
const user = {
name: 'John',
address: {
street: '123 Main St',
city: 'New York'
}
};
// Safe property access
console.log(user?.address?.street); // '123 Main St'
console.log(user?.phone?.number); // undefined (no error)
// Safe method calls
user?.getName?.(); // undefined (no error if method doesn't exist)
// Safe array access
const users = [{ name: 'Alice' }];
console.log(users?.[0]?.name); // 'Alice'