Optional Chaining (?.
) in JavaScript
Introduction
Optional chaining (?.
) is a feature in JavaScript that allows you to safely access deeply nested object properties without explicitly checking each level for null
or undefined
. If a property does not exist, it returns undefined
instead of throwing an error.
Syntax
obj?.prop
obj?.[expr]
obj?.method?.()
Example Usage
const user = {
name: "John Doe",
address: {
city: "New York",
zip: "10001"
}
};
console.log(user?.name); // "John Doe"
console.log(user?.address?.city); // "New York"
console.log(user?.contact?.phone); // undefined (no error)
Using Optional Chaining with Functions
const person = {
greet: function () {
return "Hello!";
}
};
console.log(person?.greet?.()); // "Hello!"
console.log(person?.sayBye?.()); // undefined (no error)
Using Optional Chaining with Arrays
const users = [{ name: "Alice" }, { name: "Bob" }];
console.log(users?.[1]?.name); // "Bob"
console.log(users?.[2]?.name); // undefined (no error)
Benefits of Optional Chaining
- Prevents runtime errors due to
null
orundefined
values. - Makes code cleaner and more readable.
- Useful when working with APIs or dynamic objects.