Optional Chaining: The Graceful Accessor
Let’s say you have an object representing a user, and you want to access their address.
In the past, you might have done something like this:
const user = {
name: "Alice",
address: { street: "123 Main St" }
};
const street = user.address && user.address.street;
console.log('Street: ', street); // Output: 123 Main St
But what happens if the user object doesn’t have an address property or the address object doesn’t have a street property?
You’d get an error!
Enter Optional Chaining!
This operator (?.
) lets you access nested properties safely, returning undefined if any part of the chain is missing.
For example:
const user = {
name: "Bob"
};
const street = user.address?.street;
console.log('Street: ', street); // Output: undefined
See how much cleaner and concise the code is?
Nullish Coalescing
The Default Value Defender.
Now, let’s imagine you want to assign a default value to a variable if it’s null or undefined. Traditionally, you might use the OR operator (||
). However, this can lead to unexpected behavior if the variable holds a "falsy" value like 0
or an empty string.
Why it's useful:
- It simplifies code by replacing verbose if statements or ternary operators.
- It focuses specifically on null and undefined, unlike the logical OR operator (||) which also treats falsy values (like 0 or empty strings) as "missing".
let userSettings = null; // Imagine this comes from an API or user input
// Without nullish coalescing:
let theme = userSettings !== null && userSettings !== undefined ? userSettings.theme : 'light';
// With nullish coalescing:
let theme = userSettings?.theme ?? 'light'; // If userSettings.theme is null or undefined, 'light' is used
Key points:
- The left side of ?? is evaluated first.
- If the left side is null or undefined, the right side is returned.
- Otherwise, the left side is returned.
It's especially handy when dealing with optional properties or potentially missing data.
Optional chaining and nullish coalescing help you write more readable, robust, and error-resistant code.