QuestionsJavaScript

Deep get by path string (lodash.get)

Safe AccessMediumJavaScript

Implement get(obj, path, defaultValue) that safely reads a nested value via a 'a.b[0].c' path, returning the default if any link is missing.

What it tests

Path parsing (dot + bracket notation), null-safe traversal, and distinguishing 'missing' from a legitimately-undefined leaf.

Approach & answer

This is the runtime cousin of optional chaining, needed when the path is a DYNAMIC string (config keys, form field names, i18n). The algorithm: normalise the path into an array of keys, then walk the object one key at a time, bailing to the default the instant the current value is null/undefined. Path normalisation is the tricky part — you must support both dot notation and bracket/array indices, so convert `a[0].b` into `['a','0','b']`: a common approach is `path.replace(/\[(\w+)\]/g, '.$1')` to turn brackets into dots, strip a leading dot, then split on '.'. (If the caller already passes an array of keys, use it directly.) Walk with a guard: `while (obj != null && index < length) { obj = obj[keys[index++]]; }`. The important subtlety is the RETURN condition: only return the default when traversal stopped EARLY (we didn't consume the whole path because we hit a nullish link) — i.e. `return index === length ? obj : defaultValue`. That means if the full path resolves to a real `undefined` leaf, you return that undefined, not the default — matching lodash semantics. This cleanly handles arrays (numeric string keys index them), missing intermediate objects, and a nullish root.

Use this technique when

Reading deeply nested config/API data by a computed string path, form libraries, and anywhere optional chaining can't be written literally.

Complexity

O(d) where d is path depth.

References

js