The optional chaining operator (?.) is used to safely access deeply nested object properties without throwing errors if a reference is null or undefined.

It was introduced in ES2020.

1.Basic Syntax

object?.property
object?.[expression]
object?.method()
  • ?. stops the evaluation if the value before it is null or undefined
  • Returns undefined instead of throwing an error

2.Example: Accessing Nested Properties

Without optional chaining:

const user = { name: "Zaman" };

console.log(user.address.city);
// ❌ Error: Cannot read property 'city' of undefined

With optional chaining:

console.log(user.address?.city);
// undefined (no error)

3.Optional Chaining With Arrays

const users = [{ name: "Zaman" }];
 console.log(users[0]?.name); // Zaman 
console.log(users[1]?.name); // undefined

✔ Safely access array elements that may not exist

4.Optional Chaining With Methods

const user = {
name: "Zaman",
greet() { return "Hello"; }
};
console.log(user.greet?.()); // Hello
console.log(user.sayHi?.()); // undefined

✔ Calls method only if it exists

5.Optional Chaining With Dynamic Properties

const key = "city";
const user = { address: { city: "Dhaka" } };
console.log(user.address?.[key]); // Dhaka
console.log(user.location?.[key]); // undefined

6.Optional Chaining With Function Calls

const user = {
getName() { 
return "Zaman"; 
}
};
console.log(user.getName?.()); // Zaman
console.log(user.getAge?.()); // undefined

✔ Prevents “Cannot read property of undefined” errors

7.Combining Optional Chaining With Nullish Coalescing

const user = { name: "Zaman" }; 
const city = user.address?.city ?? "Dhaka"; 
console.log(city); // Dhaka

✔ Use ?? to provide default value if undefined or null

Categorized in:

Javascript,