Optional Chaining Operator “?.” in JavaScript

In JavaScript, the ?. is called the “optional chaining” operator. It is a feature introduced in ECMAScript 2020 (ES11) . It is used to simplify accessing object properties and calling object methods , especially when dealing with nested or deeply nested objects.

The optional chaining operator (?.) allows to safely access Objects properties or Object methods without worrying about whether the property or method exists. If the property or function is null or undefined, the expression returns undefined instead of throwing an error, making your code more robust and less prone to runtime errors.

Basic syntax of the optional chaining operator:

object?.property
object?.method()

Examples:

  1. Accessing Object Properties:
const person = {
  name: 'John',
  age: 30,
};
console.log(person.name); // Output: 'John'
console.log(person.address); // Output: undefined (property doesn't exist)
// With optional chaining:
console.log(person?.name); // Output: 'John'
console.log(person?.address); // Output: undefined (no error thrown)
  1. Calling Object Methods:
const calculator = {
  add: function (a, b) {
    return a + b;
  },
};
console.log(calculator.add(5, 3)); // Output: 8
console.log(calculator.subtract(5, 3)); // Output: TypeError (method doesn't exist)
// With optional chaining:
console.log(calculator?.add(5, 3)); // Output: 8
console.log(calculator?.subtract(5, 3)); // Output: undefined (no error thrown)

By using the optional chaining operator, you can write more concise and safe code, especially when working with complex data structures or APIs where certain properties or functions might not always be present.

Scroll to Top