Write a function `getCity(user)` that safely accesses `user.address.city` and returns `"Unknown"` if any part of the chain is null/undefined.
Problem Statement
Write a function `getCity(user)` that safely accesses `user.address.city` and returns `"Unknown"` if any part of the chain is null/undefined.
Complexity
Time Complexity: -
Space Complexity: -
Hints
š” Hint 1:
Without optional chaining, accessing a property on undefined throws an error.
š” Hint 2:
Optional chaining (?.) short-circuits and returns undefined if the left side is null/undefined.
š” Hint 3:
return user?.address?.city ?? "Unknown";
ā
Solution:
```javascript
function getCity(user) {
return user?.address?.city ?? "Unknown";
}
```