skip to Main Content

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.

2

Answers


  1. 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 coalescing operator prevents the TypeError and returns a null when you try to call "a?.b", the null is then passed to the next field 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;
    
    Login or Signup to reply.
  2. In JavaScript, the optional chaining operator (?.) stops the evaluation and returns undefined as soon as it encounters an undefined or null value in the chain. In your original code a?.b.c, if a is undefined, it stops at a?.b and returns undefined. However, when you try to access property c on undefined, it throws a TypeError.

    You need to handle the scenario where either a is undefined or b is undefined, you can achieve this by using conditional statements or a default value. Here are three alternatives:

    1. Using Optional Chaining:

      const result = a?.b?.c // undefined
      
      
    2. Using Conditional Statements:

      const result = (a && a.b && a.b.c) || undefined;
      
      
    3. Using Default Value + Optional Chaining:

      const result = a?.b?.c ?? undefined;
      
      

    In all cases, if any part of the chain is undefined, the result will be undefined. The third approach uses the nullish coalescing operator (??) to explicitly check for null or undefined and provide a default value.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search