Optional Chaining (?.) is a feature in JavaScript that allows you to safely access deeply nested object properties without having to manually check if each reference in the chain exists.
🔹 Syntax:
object?.property
object?.[expression]
object?.method?.()
🔸 Example without Optional Chaining:
let user = {};
console.log(user.address.city); // ❌ Error: Cannot read property 'city' of undefined
🔸 Example with Optional Chaining:
let user = {};
console.log(user.address?.city); // ✅ Output: undefined (no error)
🔹 Use Cases:
-
Access nested properties:
const city = user?.address?.city; -
Call methods if they exist:
user?.getProfile?.(); -
Access array elements:
const firstFriend = user?.friends?.[0];
✅ Benefits:
- Prevents runtime errors.
- Makes code cleaner and more readable.
- Useful for working with optional data, API responses, or deeply nested structures.