Undefined to Null solution and explanation
14 more videos on this problem
Null vs Undefined - Beau teaches JavaScriptfreeCodeCamp.org · 3:45 · 62K views
Null vs Undefined in JavaScript - Explained VisuallyLucas Paganini · 2:48 · 22K views
JavaScript Fundamentals: Checking for null and undefinedAll Things JavaScript, LLC · 11:13 · 20K views
JavaScript Null vs Undefined - #JavaScriptJanuarycodeSTACKr · 1:30 · 11K views
Best Way to Check 'Null', 'Undefined' or 'Empty' in JavaScriptWebStylePress · 4:52 · 5K views
TypeScript: Undefined vs null - Stop using null (even in JavaScript)Patrick Desjardins · 7:25 · 5K views
The difference between Null and Undefined in JavaScriptRichard Oliver Bray · 0:53 · 3K views
📦 null, undefined & the mystery box 🕵️♂️ #coding #javascriptStack Overflowed · 0:13 · 1K views
Null vs Undefined in JavaScript.Tech with Saran · 0:32 · 1K views
Undefined vs Null! #coding #javascriptAhmed Gagan · 0:49 · 997 views
undefined vs null || java script interview questionsBeacon · 3:00 · 245 views
What is the Difference Between Undefined and NULL? - Javascript Interview QuestionDavid Anuson · 3:19 · 226 views
Null vs undefined| #shorts #null #undefined #javascript #programming #programmerscoding with krishna · 0:16 · 177 views
Is there a standard function to check for null, undefined, or blank variables in JavaScriptFahad Ali J. · 2:42 · 158 views
How to Check for an Empty, Undefined, or Null String in JavaScriptTech Nursery · 1:37 · 2 views
The problem
Given a deeply nested object or array obj, return the object obj with any undefined values replaced by null.
undefined values are handled differently than null values when objects are converted to a JSON string using JSON.stringify(). This function helps ensure serialized data is free of unexpected errors.
Example 1:
Input: obj = {"a": undefined, "b": 3}
Output: {"a": null, "b": 3}
Explanation: The value for obj.a has been changed from undefined to null
Example 2:
Input: obj = {"a": undefined, "b": ["a", undefined]}
Output: {"a": null,"b": ["a", null]}
Explanation: The values for obj.a and obj.b[1] have been changed from undefined to null
Constraints:
objis a valid JSON object or array2 <= JSON.stringify(obj).length <= 105
Approach overview
Problem Overview: You receive a JavaScript value that may contain nested objects or arrays. The task is to traverse the structure and replace every undefined value with null, while preserving the original structure and other values.
Approach 1: Recursive DFS Traversal (O(n) time, O(h) space)
The cleanest solution uses recursion to perform a depth-first traversal over the structure. Start by checking the type of the current value. If the value is exactly undefined, return null. If the value is an array, iterate through each index and recursively process each element. If the value is an object, iterate over its keys and recursively transform each property value.
The key insight is that arrays and objects are the only structures that can contain nested values requiring transformation. Primitive values like numbers, strings, and booleans can be returned directly. During traversal, every nested branch is visited exactly once, ensuring linear processing of the entire structure.
This approach naturally mirrors the hierarchical shape of JSON-like data. Each recursive call handles a smaller substructure until reaching primitives. Because recursion depth equals the nesting depth, auxiliary space depends on the maximum depth h. This pattern is closely related to techniques used in recursion and depth-first search for hierarchical data processing.
In practice, the algorithm works well for configuration objects, API responses, or parsed JSON-like structures where missing values must be normalized before serialization or storage.
Approach 2: Iterative Stack Traversal (O(n) time, O(n) space)
An iterative alternative replaces recursion with an explicit stack. Push the root value onto the stack and repeatedly process items until the stack is empty. When encountering arrays or objects, push their children onto the stack for later processing. When a value equals undefined, replace it with null.
This version performs the same logical traversal but avoids recursion depth limits. Each node is still processed once, giving O(n) time complexity. However, the stack may temporarily store many nodes, producing O(n) space usage in the worst case.
Iterative traversal is useful when the nesting depth could exceed the call stack limit or when environments discourage deep recursion.
Recommended for interviews: The recursive DFS approach is typically expected. It demonstrates clear understanding of object/array traversal and recursive decomposition. Mentioning the iterative stack alternative shows awareness of recursion limits and practical implementation trade‑offs.
Solution
function undefinedToNull(obj: Record<any, any>): Record<any, any> {
for (const key in obj) {
if (typeof obj[key] === 'object') {
obj[key] = undefinedToNull(obj[key]);
}
if (obj[key] === undefined) {
obj[key] = null;
}
}
return obj;
}
/**
* undefinedToNull({"a": undefined, "b": 3}) // {"a": null, "b": 3}
* undefinedToNull([undefined, undefined]) // [null, null]
*/Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Recursive DFS Traversal | O(n) | O(h) | Best general solution for nested objects/arrays with manageable depth |
| Iterative Stack Traversal | O(n) | O(n) | When recursion depth could exceed call stack limits |
Frequently asked questions
Is Undefined to Null easy or hard?
The problem is rated Medium because it requires careful handling of multiple data types and nested structures. The traversal logic is straightforward, but correctly distinguishing primitives, arrays, and objects is the key challenge.
Undefined to Null Python/Java solution
The core idea remains the same across languages: recursively traverse dictionaries/maps and lists/arrays, replacing undefined-like values with null or None. JavaScript and TypeScript implementations are most common because the problem originates from JavaScript semantics.
How to solve Undefined to Null in O(n)?
Traverse the structure using recursion or a stack. When encountering undefined, return null. If the value is an array or object, iterate through its elements or keys and recursively process each child. Since each node is visited once, the overall complexity remains O(n).
What is the best approach for Undefined to Null?
The most efficient approach is a recursive depth-first traversal of the object or array. Each value is inspected once, and undefined values are replaced with null while traversing nested structures. This solution runs in O(n) time and O(h) space, where h is the maximum nesting depth.
Is Undefined to Null asked at Google/Amazon/Meta?
Problems involving recursive traversal of nested objects or JSON-like structures appear in frontend and JavaScript-focused interviews at companies like Google, Amazon, and Meta. The question tests understanding of recursion, object iteration, and data normalization.
What data structure is used in Undefined to Null?
The solution primarily relies on recursive traversal of JavaScript objects and arrays. Conceptually it behaves like a depth-first search over a tree-like structure where each property or element acts as a node.
What is the time complexity of Undefined to Null?
The time complexity is O(n) because every element, object property, or array entry in the structure is visited exactly once during traversal. Space complexity is O(h) with recursion, where h represents the nesting depth of the structure.
