JavaScript Optional Chaining
Optional chaining (?.) lets you safely access properties or methods when a value might be null or undefined.
Without optional chaining, accessing a property on undefined can throw an error.
JavaScript
Safely accessing a nested property.
const user = {
profile: {
name: "Alex"
}
};
console.log(user.profile?.name);
console.log(user.address?.city);
You can chain multiple optional accesses when working with deeply nested data.
JavaScript
Accessing deeply nested properties safely.
const response = {
user: {
account: {
settings: {
theme: "dark"
}
}
}
};
console.log(response.user?.account?.settings?.theme);
Optional chaining can safely access array elements when the array might not exist.
JavaScript
Safely accessing an array element.
const users = undefined;
console.log(users?.[0]);
Use ?.() when a function may not exist.
JavaScript
Calling a function only when it exists.
const user = {
greet() {
return "Hello!";
}
};
console.log(user.greet?.());
console.log(user.login?.());
Optional chaining works well with the nullish coalescing operator to provide fallback values.
JavaScript
Providing a fallback for missing data.
const user = {};
const city = user.address?.city ?? "Unknown";
console.log(city);
Optional chaining is especially useful when handling API responses where some fields may be missing.
JavaScript
Reading optional API response data.
const data = {
customer: {
name: "Alex"
}
};
const email = data.customer?.contact?.email ?? "No email";
console.log(email);
Optional chaining makes property, array, and function access safer and cleaner when values may be null or undefined.