Coding Challenge Practice - Question 81

Published: (December 17, 2025 at 05:07 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Task

Implement a function that replaces undefined values with null throughout a given input, handling primitives, arrays, and objects recursively.

Approach

  1. Base case – If the argument is exactly undefined, return null.
  2. Arrays – Detect with Array.isArray. Create a new array of the same length, recursively process each element, and return the new array.
  3. Objects – For non‑null objects, create a new empty object, iterate over its own enumerable keys, recursively process each value, and assign the result back to the corresponding key.
  4. Other values – Return the argument unchanged.

Implementation

function undefinedToNull(arg) {
  // Replace undefined with null
  if (arg === undefined) return null;

  // Handle arrays
  if (Array.isArray(arg)) {
    const result = new Array(arg.length);
    for (let i = 0; i < arg.length; i++) {
      result[i] = undefinedToNull(arg[i]);
    }
    return result;
  }

  // Handle objects (excluding null)
  if (arg !== null && typeof arg === 'object') {
    const result = {};
    for (const key in arg) {
      if (Object.prototype.hasOwnProperty.call(arg, key)) {
        result[key] = undefinedToNull(arg[key]);
      }
    }
    return result;
  }

  // Primitive values (including null) are returned as‑is
  return arg;
}
Back to Blog

Related posts

Read more »

Day 1/30 back to DSA challenge

DSA - Reviewed notes on DSA. - Solved the Two Sum problem using a hashmap and the complement technique. - Instead of storing each element and checking sums, st...

Objects in JavaScript

What is Objects? - An object is a variable that can hold multiple variables. - It is a collection of key‑value pairs, where each key has a value. - Combination...