Scriptdrill

Level 4: Data shaping Exercise 33 of 45 Pro

Read a nested value by path

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

Follow a dot path like `"user.address.city"` or `"items.0.id"` (numbers index arrays) into `obj` and return the value there. If a step along the way is missing, `null` or `undefined`, or the final value is `undefined`, return `fallback`. Real values such as `0`, `false`, `""` and a final `null` are returned as they are. An empty path returns `obj`.

What this exercise teaches

Checking for null or undefined before each step prevents a TypeError on missing branches. Testing the final value with === undefined, instead of ||, keeps falsy but real values like 0, false, "" and null.

A hint if you get stuck

Split the path on `.` and walk one key at a time. Stop with `fallback` as soon as the current value is `null` or `undefined`. Avoid `||`, which also replaces `0` and `""`.

This exercise is part of Pro

Pro unlocks all 45 exercises, with worked solutions and progress saved to your account. The free exercises work without an account.

You create a free account first, so Pro is attached to it.

Monthly is charged today and then every month until you cancel, in one click from your account page. Lifetime is one payment with no renewals. Full refund within 14 days of paying.

Start with the free exercises

More exercises in Data shaping