Cannot convert undefined or null to Object in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Cannot convert undefined or null to Object in JavaScript #

The "Cannot convert undefined or null to Object" error occurs when we pass a null or an undefined value to a function that expects an object as a parameter. This commonly happens when using the Object.keys(), Object.values() and Object.assign() methods.

cannot convert undefined or null to object

Here are some examples of how the error occurs.

index.js
// 👇️ Cannot convert undefined or null to object Object.keys(null); // 👇️ Cannot convert undefined or null to object Object.values(undefined); // 👇️ Cannot convert undefined or null to object Object.assign(undefined, {}); const obj = undefined; // 👇️ Cannot convert undefined or null to object delete obj.property;

The methods expect to receive an object as a parameter, but we pass them null or undefined values, which causes the error.

To solve the "Cannot convert undefined or null to object" error, conditionally check if the value of the variable you're passing to the function is truthy before calling it, e.g. if (obj) {func()}. The function will not be invoked if the value is null or undefined.

index.js
const obj = undefined; if (obj) { const keys = Object.keys(obj); } else { // 👇️ this runs console.log('⛔️ Object is falsy'); }

We make sure that we don't call the method passing it null or undefined by checking if the value of the obj variable is truthy.

The truthy values in JavaScript are all the non-falsy values.

The list of falsy values consists of: false, null, undefined, 0, "" (empty string), NaN (not a number).

An alternative approach is to use the logical OR (||) operator to provide an object as the backup, incase the value is falsy.

index.js
const obj = undefined; Object.keys(null || {});

null is a falsy value, so the logical OR (||) operator returns the value to the right-hand side.

The logical OR operator checks if the value to the left is truthy and if it is, it returns it.

In all other cases, it returns the value to the right.

This covers us in the scenario where the value is null or undefined.

Conclusion #

The "Cannot convert undefined or null to Object" error occurs when we pass a null or an undefined value to a function that expects an object as a parameter. This commonly happens when using the Object.keys(), Object.values() and Object.assign() methods.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.