[JavaScript] What is Optional chaining (?.)?

·

1 min read

[JavaScript] What is Optional chaining (?.)?

The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.

Syntax

obj.val?.prop
obj.val?.[prop]
obj.func?.(args)

Examples

const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah',
  },
};

console.log(adventurer.dog.name);
// TypeError: Cannot read properties of undefined

console.log(adventurer.dog?.name);
// undefined

console.log(adventurer.someNonExistentMethod?.());
// undefined

Tips

  1. Variables before ?. must be declared. The error occurs if the variable is not declared.

     console.log(user?.address);
     // ReferenceError: user is not defined
    
  2. Don't abuse optional chaining. Optional chaining should only be used for objects that do not need to exist.

  3. If the left operand is null or undefined, the expression after ?. will not be evaluated. (Short-circuiting)

     let user = null;
     let x = 0;
    
     user?.sayHi(x++); // Nothing happens
    
     console.log(x); 
     // 0
    
  4. Optional chaining is not valid on the left-hand side of an assignment. But, ?. can be used in combination with delete.

     delete user?.name; // Delete user.name if user exists
    
     user?.name = "Violet"; 
     // SyntaxError: Invalid left-hand side in assignment
     // The error occurs because It is same with undefined = "Violet"