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
usernull/undefined hai →undefinedreturn (error nahi). - Agar
user.addressnull/undefined hai →undefinedreturn (error nahi). - Agar
user.address.cityexist karta hai → value return. - Without
?.:user.address.city→ error ifuseroraddressis null.
Part 2: Nullish coalescing
?? 'Unknown'??→ nullish coalescing operator:- Agar left side
nullyaundefinedhai → 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
Category
Objects & JSON
20 Exercises