Learning object 30 of 100
Optional chaining laboratory
Compare a plain property chain with an optional chain on data that may be missing, then compare ||, ?? and default parameters on 0, "", false, null and undefined.
Loading…
What it shows
?. checks the value on its left and returns undefined instead of throwing when it is null or undefined. ?? falls back only for null and undefined, while || falls back for every falsy value, including 0 and "". A default parameter replaces only undefined.
Guided experiment
- Choose
data.user.address.city. Why does the plain chain throw? - Choose
data.tags[0]. Why does nothing throw even though there is no tag? - Test the value
0and thennullin the fallback section.
Predict
What is 0 || 10 compared with 0 ?? 10?
Related
Lessons: Lesson 43: Optional chaining, Lesson 44: Nullish coalescing and default values
Projects: Project 9: Shopping Cart Price Calculator
Source: web/assets/js/objects/object-030.js in the companion repository.