Solve - Cannot convert undefined or null to Object in JS

avatar

Borislav Hadzhiev

Wed Nov 03 20212 min read

Cannot convert undefined or null to Object #

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

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'); }

By checking if the value of the obj variable is truthy before passing it to the Object.keys() method, we make sure that we don't call the method passing it null or undefined.

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 || {});

Because null is a falsy value 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.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee