Skip to main content

JavaScript Optional Chaining — exercises and bug fixes

5 hands-on exercises and 5 find-the-bug challenges for the JavaScript Optional Chaining lesson. Every one is checked automatically in the browser — write the code, run it, and the tests tell you what still fails.

Exercises(5)

  1. 1

    Read a missing nested property

    easy10 min

    Use optional chaining to read a city that is not there, and show its type.

  2. 2

    Read a nested property that exists

    easy10 min

    Use optional chaining to read a city that is present.

  3. 3

    Chain two levels

    easy10 min

    Use optional chaining twice on a path that stops halfway.

  4. 4

    Use the bracket form

    easy10 min

    Safely read the first item of an array that does not exist.

  5. 5

    Keep a real zero

    medium10 min

    Show that optional chaining does not replace a value of zero.

Find the bug(5)

  1. 1

    Fix the unsafe nested read

    easy8 min

    The address is missing, so the path needs guarding.

  2. 2

    Fix the question mark in the wrong place

    easy8 min

    The guard is on the wrong step of the path.

  3. 3

    Fix the missing bracket form

    easy8 min

    An index needs ?.[ ] rather than a plain dot.

  4. 4

    Fix the long guard chain

    easy8 min

    The nested checks work but are hard to read; use optional chaining.

  5. 5

    Fix the zero treated as missing

    easy8 min

    Optional chaining only guards null and undefined, so a real zero must survive.

Ready to write the code?

The editor, the automatic checks and the worked solutions open up with an account.

Open the workspace