Objects

Optional Chaining

Optional Chaining

Nested object reads fail when an intermediate value is null or undefined. Optional chaining stops the read at that point and produces undefined instead of throwing an error.

This is common with profile data, API responses, and configuration objects that may be incomplete.

Your task: Write getCity(user) so it returns the user's city when user.profile.address.city exists. Return "Unknown" when any part of that path is missing.

Free with a JS Exercises account

Sign in to start coding, run your solution, and keep your progress saved for later. No payment needed.

By continuing, you agree to our Terms and Privacy Policy. We'll send occasional product updates and news. You can unsubscribe anytime.

Optional Chaining

Nested object reads fail when an intermediate value is null or undefined. Optional chaining stops the read at that point and produces undefined instead of throwing an error.

This is common with profile data, API responses, and configuration objects that may be incomplete.

Your task: Write getCity(user) so it returns the user's city when user.profile.address.city exists. Return "Unknown" when any part of that path is missing.

Free with a JS Exercises account

Sign in to start coding, run your solution, and keep your progress saved for later. No payment needed.

By continuing, you agree to our Terms and Privacy Policy. We'll send occasional product updates and news. You can unsubscribe anytime.

Console

Run code to see output.