Exercise 1: Safe Nested Read (optional chaining)

Problem Statement

Function `getCity(user)` banao jo `user.address.city` return kare. Missing ho to "Unknown".

Sample Output:

getCity({address: {city: "Mumbai"}}) => "Mumbai"
getCity({address: {}}) => "Unknown"
getCity(null) => "Unknown"

Solution

const getCity = (user) => user?.address?.city ?? 'Unknown';

Explanation

Overall Goal:

  • Nested object properties ko safely access karna.
  • Missing properties handle karna (error avoid).

Single Line Solution:

  • const getCity = (user) => user?.address?.city ?? 'Unknown';

Part 1: Optional chaining

  • user?.address?.city
  • ?. → optional chaining operator:
  • Agar user null/undefined hai → undefined return (error nahi).
  • Agar user.address null/undefined hai → undefined return (error nahi).
  • Agar user.address.city exist karta hai → value return.
  • Without ?.: user.address.city → error if user or address is null.

Part 2: Nullish coalescing

  • ?? 'Unknown'
  • ?? → nullish coalescing operator:
  • Agar left side null ya undefined hai → right side use karo.
  • Agar left side value hai → wahi use karo.

Example:

  • getCity({address: {city: "Mumbai"}})"Mumbai".
  • getCity({address: {}})undefined"Unknown".
  • getCity(null)undefined"Unknown".

Real world:

  • API responses: data incomplete ho sakta hai.
  • Form data: optional fields handle karna.
  • User profiles: nested data access.

Navigation

Previous

No previous exercise

Next

Exercise 2

View All Categories