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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { data: { school: { class: { student: { name: 'pikachu' } } } } } const name = data.school.class.name; |
The above treatment will easily give you a bug if the data returns null
1 2 3 4 5 6 7 8 | { data: null } const name = data.school.class.name; Uncaught TypeError: Cannot read property 'school' of null |
To handle the above case, the traditional way is
1 2 3 4 5 6 | const name = data && data.school && data.school.class && data.school.class.student && data.school.class.student.name; |
Quite cumbersome …
2. Optional chaining
Optional chaining
is a feature that helps you access an object’s property faster and easier
1 2 3 4 5 6 7 8 | { data: null } const name = data?.school?.class?.student?.name; name = undefined |
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
1 2 | name = data?.['school']?.['class']?.['student']?.['name']; |
3. Attention
Optional chaining
is handy, but shouldn’t overdo it. We should only use it for property
as optional
.
1 2 3 4 5 6 7 8 9 10 11 12 | { data: { school: { class: { student: { name: 'pikachu' } } } } } |
With the above example, school
is required and the class
does not have it, we should write
1 2 | const name = data.school?.class?.student?.name; |
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.