The error “TypeError: Cannot convert undefined or null to object” happens when JavaScript attempts to convert null
and undefined
to an object. Below you can see examples of when this error occurs.
// ❌ Uncaught TypeError: Cannot convert undefined or null to object at Function.assign
Object.assign(undefined, {});
Object.assign(null, {});
// ❌ TypeError: Cannot convert undefined or null to object at Function.keys
Object.keys(undefined);
Object.keys(null);
// ❌ TypeError: Cannot convert undefined or null to object at Function.values
Object.values(undefined);
Object.values(null);
In the previous example, notice how the Object.assign()
, Object.keys()
, and Object.values()
methods expect a parameter o
equivalent to any JavaScript object {}
.
? Interestingly, if you attempt passing a number, a string, or even a boolean when using the Object.assign()
, Object.keys()
, and Object.values()
methods, JavaScript won’t generate an error.
// ✅ No errors generated
Object.assign(1, {});
Object.assign(true, {});
Object.assign('Hello', {});
// ✅ No errors generated
Object.keys(1);
Object.keys(true);
Object.keys('Hello');
// ✅ No errors generated
Object.values(1);
Object.values(true);
Object.values('Hello');
What happens in this scenario is JavaScript attempts to identify if the values of the received parameters have the expected value type, such as a boolean, a string, a number, an object, or an array (which is a special kind of object), etc.
? If the values of the received parameters are not an expected value type, for instance, an object, JavaScript will automatically attempt to transform the values to a given value type.
That’s why the Object.assign()
, Object.keys()
, and Object.values()
methods didn’t fail even after a value passed is different not an object.
Table of Contents
How to solve or prevent getting the error “TypeError: Cannot convert undefined or null to object”
Fortunately, here there are different alternatives to solve or prevent getting the error “TypeError: Cannot convert undefined or null to object”:
- Use conditional checks prior to triggering methods expecting an object.
- Use the nullish coalescing operator (
??
) to use a fallback value. - Use the logical OR (
||
) operator to use a fallback value. - Use Try/Catch statements to detect errors.
Let’s see the examples of the solutions mentioned above. However, instead of showing the examples by explicitly passing undefined
s and null
s, you will see a more realistic scenario.
const CARS = [
{
year: 2012,
brand: "Dodge",
model: "Challenger",
color: "Black"
}
];
// the value of the 'toyota variable will be undefined
const toyota = CARS.find(car => {
return car.brand === "Toyota";
});
// ❌ TypeError: Cannot convert undefined or null to object at Function.values
const toyotaValues = Object.values(toyota);
In the previous snippet of code, the toyota
variable is undefined because the CARS
array doesn’t contain an element with a Toyota brand after running the predicate passed to the array.find()
method on all the elements of the array. In fact, there’s always the possibility of expecting an undefined value from running the array.find()
.
Use conditional checks prior to triggering methods expecting an object
To fix the error TypeError: Cannot convert undefined or null to object at Function.values
caused in the example above, use conditional checks prior to triggering the Object.values
method to ensure the toyota
variable is an object. Here are examples of different checks you could do.
let toyotaValues = [];
// ? Use the double exclamation marks or "double bangs" to cast a true Boolean value
// in case toyota variable is an object
if (!!toyota) {
toyotaValues.push(...(Object.values(toyota));
}
// ? Use the keyword typeof to detect the type of the value of toyota
if (typeof toyota !== 'undefined') {
toyotaValues.push(...(Object.values(toyota));
}
Use the nullish coalescing operator (??
) to use a fallback value
Another solution is to use the nullish coalescing operator (??
) to use a fallback value object in case the original value is undefined
or null
.
// ✅ Using the nullish coalescing operator is a clean way to prevent errors
// ocurred from using undefined or null values
const toyotaValues = Object.values(toyota ?? {
year: 2018,
brand: "Toyota",
model: "Prius",
color: "Black"
};
In this way, if the toyota
variable is undefined
or null
, the Object.values()
method will use the fallback object value.
{
year: 2018,
brand: "Toyota",
model: "Prius",
color: "Black"
}
Use the logical OR (||
) operator to use a fallback value
Similar to the previous solution, you can use the logical OR (||
) operator to use a fallback value object in case the original value is undefined
or null
.
// ✅ Using the logical OR (||) is a clean way to prevent errors
// ocurred from using undefined or null values
const toyotaValues = Object.values(toyota ?? {
year: 2018,
brand: "Toyota",
model: "Prius",
color: "Black"
};
Use Try/Catch statements to detect errors
Finally but not least, you can wrap the logic of the code between a try and catch to prevent the code from crashing at runtime.
try {
const CARS = [
{
year: 2012,
brand: "Dodge",
model: "Challenger",
color: "Black"
}
];
// the value of the 'toyota variable will be undefined
const toyota = CARS.find(car => {
return car.brand === "Toyota";
});
// ❌ Expected Error: TypeError: Cannot convert undefined or null to object at Function.values
const toyotaValues = Object.values(toyota);
// ✅ The program doesn't crash at runtime even as the error is wrapped inside a try/catch
} catch (error) {
console.error('Oh no! There was an error ', error);
}
Conclusion
All in all, the error “TypeError: Cannot convert undefined or null to object” happens when attempting to convert a null
and undefined
values to an object. To prevent this error from happening
- Use conditional checks prior to triggering methods expecting an object.
- Use the nullish coalescing operator (??) to use a fallback value.
- Use the logical OR (||) operator to use a fallback value.
- Use Try/Catch statements to detect errors.