Home > Article > Web Front-end > Optional Chaining and Nullish Coalescing
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!
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?
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:
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
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.
The above is the detailed content of Optional Chaining and Nullish Coalescing. For more information, please follow other related articles on the PHP Chinese website!