Optional Chaining in JavaScript

Tram Ho

1. Introduction

Working with javascript, you are certainly no stranger to object types, especially when you are dealing with data received from api . And the most common way to get data from an object is through a property

The above treatment will easily give you a bug if the data returns null

To handle the above case, the traditional way is

Quite cumbersome …

2. Optional chaining

Optional chaining is a feature that helps you access an object’s property faster and easier

Optional chaining will return null if the one precedes ?. is null or undefined .

Similar to accessing object via property , we can also use optional chaining for accessing object via key

3. Attention

Optional chaining is handy, but shouldn’t overdo it. We should only use it for property as optional .

With the above example, school is required and the class does not have it, we should write

If we use optional chaining for school then in case the school is null or undefined , the code is still pass and we will take longer to debug.

Share the news now

Source : Viblo