Javascript

Use the Optional Chaining operator (?.) to safely access nested object properties without causing errors. 💡

const user = {
  name: 'Alice',
  address: {
    street: '123 Main St',
    city: 'Anytown'
  }
};

// Without optional chaining
const zipCode = user.address && user.address.zipCode;

// With optional chaining
const zipCode = user.address?.zipCode;

console.log(zipCode); // undefined (no error thrown)

// It also works with function calls
const getZipCode = user.getZipCode?.();