
Modern JavaScript (ES2020+) gave us three powerful operators that make our code shorter, safer, and cleaner which are the optional chaining, null coalescing and null coalescing assignment operators.
Usually when dealing with object properties in Javascript, we check for existence of specific property, or checking if this property not nullable, by using ternary expressions. However when properties deeply nested inside the object, we tend to do multiple checks depending on nesting level of properties.
For this (ES2020+) give us three powerful operators that make our code shorter, safer, and cleaner:
-
?.
Optional Chaining -
??
Nullish Coalescing -
??=
Nullish Coalescing Assignment
If you’ve ever written a pile of if
checks or ternary operators to guard against undefined
or null
, these are for you.
1. Optional Chaining ?.
Problem Before
Accessing nested properties was risky:
// Throws error if user or user.address is undefined const street = user.address.street;
You had to do: