Use optional chaining to read a city that is not there, and show its type.
Acceptance criteria
- 1.#out should show undefined.
JavaScript Tutorial · JavaScript Objects
These 10 tasks go with the JavaScript Optional Chaining chapter. 5 of them ask you to build something small from scratch; 5 give you code that is already broken and ask you to work out why. Set aside about 90 minutes for the whole set, though you can do them in any order.
Nothing here is marked by a person. When you press Submit, the editor checks your code against the points listed under each task and tells you straight away what passed and what didn't (you need a free account to submit). If you get stuck, there are hints, and a worked solution once you've had a go. The first 2 tasks are free; the rest are part of the practice plan.
If it's been a while since you read the chapter, here is how it starts: “JavaScript optional chaining reads a nested property without throwing when part of the path is missing.” .
1.Read a missing nested propertyexercise · easy · 10 min
Use optional chaining to read a city that is not there, and show its type.
Passes when: #out should show undefined.
2.Read a nested property that existsexercise · easy · 10 min · practice plan
Use optional chaining to read a city that is present.
Passes when: #out should show London.
3.Chain two levelsexercise · easy · 10 min · practice plan
Use optional chaining twice on a path that stops halfway.
Passes when: #out should show undefined.
4.Use the bracket formexercise · easy · 10 min · practice plan
Safely read the first item of an array that does not exist.
Passes when: #out should show undefined.
5.Keep a real zeroexercise · medium · 10 min · practice plan
Show that optional chaining does not replace a value of zero.
Passes when: #out should show 0.
6.Fix the unsafe nested readbug fix · easy · 8 min
The address is missing, so the path needs guarding.
Passes when: #out should show no city.
7.Fix the question mark in the wrong placebug fix · easy · 8 min · practice plan
The guard is on the wrong step of the path.
Passes when: #out should show London.
8.Fix the missing bracket formbug fix · easy · 8 min · practice plan
An index needs ?.[ ] rather than a plain dot.
Passes when: #out should show safe.
9.Fix the long guard chainbug fix · easy · 8 min · practice plan
The nested checks work but are hard to read; use optional chaining.
Passes when: #out should show Paris.
10.Fix the zero treated as missingbug fix · easy · 8 min · practice plan
Optional chaining only guards null and undefined, so a real zero must survive.
Passes when: #out should show 0.
Between them these tasks cover Optional chaining, Nested data and Safe access.
Looking for a different chapter? See every practice set, or switch to the interview theory questions.