FrontendAtlas
Interview Questions
Home>JavaScript interview questions> JavaScript coding challenges >Data Helper 1

Data Helper 1: Get Value by Path

intermediate
By FrontendAtlas Editorial · Updated Jan 30, 2026
Implement getByPath(obj, path, fallback?) that safely reads a nested value from an object. This is extremely common in frontend screens (reading deep API responses, feature flags, form state) and shows up often in interviews. Path rules: - path can be a dot string: "a.b.c" - or an array of keys: ["a", "b", "c"] - Numeric segments should work for arrays: "items.0.name". Requirements: 1) If the full path exists, return the value (even if it is null, false, or 0). 2) If any segment is missing, return fallback (or undefined if not provided). 3) Must not throw for nullish intermediate values. 4) No eval, no JSON stringify tricks. This tests safe traversal + edge-case correctness.

Arguments

  • obj: any — The object/array to read from.
  • path: string | (string | number)[] — Path as dot string or array of segments.
  • fallback: any — Optional value to return when the path does not exist.

Returns

any — The found value, or fallback/undefined when missing.
Examples
const data = { user: { profile: { name: 'Ada' }, flags: { pro: false } }, items: [{ name: 'x' }] };

getByPath(data, 'user.profile.name'); // => 'Ada'
getByPath(data, ['user', 'flags', 'pro']); // => false
getByPath(data, 'items.0.name'); // => 'x'
getByPath(data, 'user.profile.age', 18); // => 18
getByPath(data, 'missing.anything'); // => undefined

Solution

Overview

Traverse an object safely by path segments and return either the value or a fallback. The crucial detail is to distinguish missing properties from valid falsy values like 0, false, or ''. This makes the helper reliable for real-world API data and UI state.

1

Approach: Iterative traversal with "missing" detection (recommended)

Algorithm:

  • Normalize the path to an array of segments (split dots if needed).
  • Start with cur = obj and iterate through segments.
  • If cur is nullish at any point, return the fallback.
  • Use Object.prototype.hasOwnProperty.call(cur, seg) (or seg in cur) to check existence. If missing, return fallback.
  • Otherwise set cur = cur[seg] and continue.
  • If all segments resolve, return cur even if it is falsy.

Complexity: O(k) time, O(k) space for path normalization.

function toSegments(path) {
  if (Array.isArray(path)) return path;
  if (typeof path !== 'string') return null;
  const s = path.trim();
  if (!s) return [];
  return s.split('.');
}

export default function getByPath(obj, path, fallback) {
  const segs = toSegments(path);
  if (!segs) return fallback;

  let cur = obj;

  for (let i = 0; i < segs.length; i++) {
    const seg = segs[i];

    if (cur === null || cur === undefined) {
      return fallback;
    }

    // allow numeric indexing when segment is number or numeric string
    const key = typeof seg === 'number' ? seg : seg;

    // Only treat as missing when key is not present
    if (typeof cur === 'object' || typeof cur === 'function') {
      if (!(key in cur)) return fallback;
      cur = cur[key];
    } else {
      return fallback;
    }
  }

  return cur;
}
function toSegments(path: string | Array<string | number>): Array<string | number> | null {
  if (Array.isArray(path)) return path;
  if (typeof path !== 'string') return null;
  const s = path.trim();
  if (!s) return [];
  return s.split('.');
}

export default function getByPath(
  obj: any,
  path: string | Array<string | number>,
  fallback?: any
): any {
  const segs = toSegments(path);
  if (!segs) return fallback;

  let cur: any = obj;

  for (let i = 0; i < segs.length; i++) {
    const seg = segs[i];

    if (cur === null || cur === undefined) {
      return fallback;
    }

    const key: any = seg;

    if (typeof cur === 'object' || typeof cur === 'function') {
      if (!(key in cur)) return fallback;
      cur = cur[key];
    } else {
      return fallback;
    }
  }

  return cur;
}

Notes & Pitfalls

Pitfalls
  • Using `|| fallback` which incorrectly replaces valid values like `false`/`0`/`''`.
  • Not handling arrays (`items.0.name`).
  • Throwing when a mid-level object is `null`/`undefined`.
Edge cases
  • Empty path (`''` or `[]`) should return the object itself.
  • Value exists but is `undefined` (property present with value undefined). This should return `undefined`, not fallback (because it exists).
  • Path passed as array with numeric segments.
Techniques
  • Path normalization (string -> segments)
  • Safe iterative traversal
  • Use `in` to distinguish missing vs falsy

Resources

  • MDN – Optional chaining (related concept)

Similar questions

Data Helper 2: Set Value by PathintermediateGroup ByintermediateFormat Date in Time Zone (YYYY-MM-DD)intermediate

Guides

Frontend interview preparation guideGuideFrontend coding interview questions and prep guideBlueprintJavaScript Problems That Actually Show UpBlueprintBuild Great UI in 60 MinutesBlueprint

Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.

Open frontend interview questionsBrowse JavaScript interview questionsOpen Essential 60Open Machine Coding HubOpen Frontend Coding ChallengesOpen System DesignOpen Interview Prep GuideOpen System Design BlueprintOpen Framework Prep PathsOpen Study PlansOpen JavaScript mastery study planOpen Company PrepOpen JavaScript Framework Prep Guide
↗Incidents hub
5 / 88