optional chaining (?.) vs nullish coalescing (??) operators
What Will Happen Before the Data is Ready?
Look through your code and make sure it won’t blow up if the data isn’t ready (if the value is null). Be especially careful if the data is initialized to or can become null or undefined!
{user && user.name ? user.name : "Not loaded yet"
There are two new operators in ES2020 that can make this code simpler: optional chaining (?.) and nullish coalescing (??).
The optional chaining operator (?.) lets you safely access properties of an object that could be null.
optional chaining (?.)
The nullish coalescing operator (??) returns the right-hand side when the left side is null or undefined. It’s useful in cases where you might normally use ||, like this:
{user?.commentCount || "Not loaded yet"}
This example has a bug – it will show “Not loaded yet” when commentCount is 0. Using the ?? operator instead of ||, it’ll work correctly:
{user?.commentCount ?? "Not loaded yet"}
?? works like the OR || operator, except that it doesn’t consider 0, '' or false to be falsy.
Comments 0