In this lesson, you will learn how to handle missing values in objects using optional chaining and the nullish coalescing operator (??). Understanding how to manage undefined or missing properties is a key skill in JavaScript.
Optional chaining allows you to safely access deeply nested properties without getting an error if a property is missing. For example, if you want to get the city of a user, not all users have that information. This feature makes it easy to handle missing values.
Imagine you have a friend who shares their address. You want to know their city, but sometimes they forget to mention it. Instead of causing an error if the city is missing, optional chaining lets you check if the city exists first.
File: optionalChainingExample.js
const user = { name: 'Alice', address: { street: '123 Main St' } };
const city = user.address?.city ?? 'Unknown';
console.log(`User's city: ${city}`);
Expected Output:
User's city: Unknown
In the code example, user.address?.city uses optional chaining. It checks if address exists before trying to access city. If address is undefined, it returns undefined instead of throwing an error. The ?? operator then assigns ‘Unknown’ if city is missing. This method ensures you effectively handle missing values.
Try creating an object for a book with missing properties. Use optional chaining and the nullish coalescing operator to safely deal with undefined values in your object.
const book = { title: 'JavaScript Basics', author: { firstName: 'John' } };
const authorLastName = book.author?.lastName ?? 'Unknown';
console.log(`Author's last name: ${authorLastName}`);
For further learning, check out our lesson on What Is JavaScript? for more basics that will help you navigate JavaScript confidently.
You can also learn how tools work together by visiting our lesson on HTML, CSS, and JavaScript.