Modern JavaScript introduced new operators that make it easier to handle missing or undefined values. Two important ES2020 features are Optional Chaining (?.) and Nullish Coalescing (??). These operators help developers write safer and cleaner code when dealing with objects, properties, or default values.
They are commonly used in modern JavaScript applications and frameworks such as React, Angular, and Node.js.
Optional Chaining (?.)
Optional chaining allows developers to safely access deeply nested object properties without causing errors if a property does not exist.
Normally, accessing a property that does not exist would cause a runtime error. Optional chaining prevents this by returning undefined instead of throwing an error.
Example Without Optional Chaining
Error: Cannot read property 'city' of undefined
Example Using Optional Chaining
undefined
In this example, optional chaining prevents the error because the address property does not exist.
Optional Chaining with Functions
Optional chaining can also be used when calling functions that may not exist.
No error occurs because the function does not exist.
Nullish Coalescing Operator (??)
The nullish coalescing operator provides a default value when a variable is null or undefined.
It is similar to the logical OR operator (||), but it only checks for null or undefined values.
Example of Nullish Coalescing
Guest
Difference Between || and ??
The logical OR operator treats several values as false (such as 0, false, and empty strings). The nullish coalescing operator only checks for null or undefined.
10
0
In this example, the OR operator treats 0 as false, while the nullish operator keeps the original value.
Advantages of Optional Chaining and Nullish Coalescing
- Prevents runtime errors when accessing nested properties
- Provides safe default values
- Reduces the need for complex conditional checks
- Makes code cleaner and easier to read
Conclusion
Optional chaining and nullish coalescing are powerful modern JavaScript features that simplify working with uncertain or missing values. They help prevent runtime errors and allow developers to write cleaner and more reliable code.
These features are widely used in modern JavaScript frameworks and applications to handle dynamic data safely.
In the next tutorial, you will learn about Dynamic Imports in JavaScript, which allow developers to load modules only when they are needed.

