| Async/await deep dive | Nullish coalescing (??) | |
Optional Chaining in JavaScript |
Optional chaining (?.), introduced in ES2020, is a modern JavaScript feature that simplifies accessing properties or calling methods on deeply nested objects. It provides a concise way to handle cases where intermediate properties in an object chain might be null or undefined without throwing an error. Instead, the entire expression short-circuits and returns undefined.
Optional chaining is a feature introduced in ES2020 that allows you to safely access deeply nested object properties without having to check each level manually. If a reference is null or undefined, the expression short-circuits and returns undefined instead of throwing an error.
// Basic usage
const user = {
profile: {
name: "Alice",
pet: { type: "cat", name: "Whiskers" }
}
};
console.log(user.profile?.name); // "Alice"
console.log(user.profile?.pet?.name); // "Whiskers"
console.log(user.profile?.dog?.name); // undefined
// Optional chaining with functions
const result = user.getDetails?.(); // undefined (no error)
// Optional chaining with arrays
const items = [ { id: 1 }, null ];
console.log(items[1]?.id); // undefined
The optional chaining operator (?.) can be used in three ways:
obj?.propobj?.[expr]obj.method?.(args)This example compares the traditional method of checking for nested properties with the more concise optional chaining syntax.
//javascript
const user = {
name: "John",
address: {
city: "New York"
}
};
let city;
if (user && user.address && user.address.city) {
city = user.address.city;
}
console.log(city); // Output: New York
const noAddressUser = { name: "Jane" };
let street;
if (noAddressUser && noAddressUser.address && noAddressUser.address.street) {
street = noAddressUser.address.street;
} else {
street = "Not specified";
}
console.log(street); // Output: Not specified
//javascript
const user = {
name: "John",
address: {
city: "New York"
}
};
const city = user?.address?.city;
console.log(city); // Output: New York
const noAddressUser = { name: "Jane" };
const street = noAddressUser?.address?.street ?? "Not specified";
console.log(street); // Output: Not specified
In the second optional chaining example, the ?? (nullish coalescing) operator is used to provide a fallback value for when the optional chain returns undefined.
obj?.prop = value).??) for default valuesCombine optional chaining with default values:
const userName = user.profile?.name ?? "Guest";
| Async/await deep dive | Nullish coalescing (??) | |