Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Optional Chaining Lookup

Fundamentals: Part 1medium

Course · Section 2: JavaScript Fundamentals – Part 1 · Lecture 13: Basic Operators

Implement `getCity(user)` returning `user.address.city` using optional chaining, or the string `Unknown` when any part is missing.

Sample tests

Input: getCity({"address":{"city":"NYC"}})
Output: "NYC"
Input: getCity({})
Output: "Unknown"

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Accessing user.address.city directly throws when address is undefined.

Learning resources

  • MDN: Expressions and operators
Approach & explanation (try first)

user?.address?.city short-circuits to undefined if any link is missing, and ?? 'Unknown' supplies the default.

Loading...
⌘/Ctrl + Enter

Run your code to see results.