Search code examples
javascriptlanguage-lawyer

Optional chaining causing TypeError


I was surprised by the following behaviour:

const a = {};
a?.b.c; // throws TypeError: Cannot read properties of undefined (reading 'c')

My intention was to use this expression for when a optionally contains b, but if b is present it is expected to contain c. I had expected the expression a?.b.c to evaluate to undefined, and not throw. What expression should I have used?

I did not use a?.b?.c because I wanted it to throw if b did not contain c.


Solution

  • Edit: The code doesn't work as you expected, you will need the following

    if (a?.b) { // if b does exist (optional)
      const c = a.b.c; // check if c is undefined (compulsary)
    }
    

    In your code, the null-safe property access/optional chaining prevents the TypeError and returns a null when you try to call "a?.b", the null is then passed to the next property accessor as "(null).c" which throws an error.

    You need the question mark on both a and b to avoid the excecption

    const a = {};
    a?.b?.c;