Borislav Hadzhiev
Wed Nov 03 2021·2 min read
Photo by Leon Seierlein
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.
// 👇️ 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
.
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.
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
.