How to Resolve the "TypeError: Cannot convert undefined or null to object" in JavaScript
The TypeError: Cannot convert undefined or null to object is a common error in JavaScript that occurs when you try to perform an operation on a null or undefined value as if it were an object. This typically happens when you attempt to access properties, call methods, or use object-specific utilities on a variable that doesn't hold an object.
This guide will explain the common scenarios where this error occurs—primarily with methods like Object.keys() and Object.values()—and show you the modern, robust ways to prevent it.
The Core Problem: Operating on null or undefined
Many built-in JavaScript functions and operators are designed to work exclusively with objects. When you pass them null or undefined, they cannot proceed and throw a TypeError.
Problem: methods like Object.keys(), Object.values(), and Object.entries() all expect an object as their argument.
let myObject = null;
// ⛔️ TypeError: Cannot convert undefined or null to object
const keys = Object.keys(myObject);
The same error occurs when you try to access a property on a null or undefined value.
let user = undefined;
// ⛔️ TypeError: Cannot read properties of undefined (reading 'name')
const name = user.name;
Solution 1 (Recommended): The Nullish Coalescing Operator (??)
The nullish coalescing operator (??) is a modern and highly readable way to provide a default value when a variable is null or undefined. This is the perfect tool for preventing this error when working with object utilities.
Solution:
const myObject = null;
// If `myObject` is null or undefined, use an empty object `{}` as a fallback.
const keys = Object.keys(myObject ?? {});
console.log(keys); // Output: []
This is the recommended best practice because it's concise and clearly expresses the intent: "Use this value, but if it's nullish, use this default instead."
Solution 2 (Also Excellent): Optional Chaining (?.)
When you are trying to access a property on an object that might be null or undefined, the optional chaining operator (?.) is the ideal solution. It "short-circuits" the expression, returning undefined instead of throwing an error.
const user = null;
// If `user` is null or undefined, the expression stops and returns `undefined`.
const name = user?.name;
console.log(name); // Output: undefined
You can combine this with the nullish coalescing operator to provide a default value.
const name = user?.name ?? 'Guest';
console.log(name); // Output: "Guest"
Solution 3 (Classic): The if Statement Check
The most traditional way to prevent this error is to explicitly check if the variable holds a valid object before you try to use it.
const myObject = null;
let keys = []; // Initialize with a default value
// Only try to get the keys if `myObject` is "truthy"
if (myObject) {
keys = Object.keys(myObject);
}
console.log(keys); // Output: []
While this works perfectly, the modern ?? and ?. operators are generally preferred for their conciseness.
Practical Example: Getting the Keys of a Potentially Null Object
This example demonstrates a reusable function that safely gets the keys of an object, always returning an array.
/**
* Safely gets the keys of an object.
* @param {object | null | undefined} obj The object to get keys from.
* @returns {Array<string>} An array of the object's keys, or an empty array.
*/
function getKeysSafely(obj) {
// Use the nullish coalescing operator to provide a fallback empty object.
return Object.keys(obj ?? {});
}
// Example Usage:
const user = { id: 1, name: 'Alice' };
const noUser = null;
console.log(getKeysSafely(user)); // Output: ['id', 'name']
console.log(getKeysSafely(noUser)); // Output: []
Conclusion
The TypeError: Cannot convert undefined or null to object is a preventable error that occurs when you don't account for potentially "empty" variables.
- When using object utilities like
Object.keys(), the recommended best practice is to provide a default value with the nullish coalescing operator (??):Object.keys(myVar ?? {}). - When accessing a property on a potentially nullish object, the recommended best practice is to use optional chaining (
?.):myVar?.myProp. - A classic
ifstatement is a perfectly valid and readable way to guard your code against this error.
By defensively checking for null and undefined values, you can write more robust and error-free code.