The “cannot read property ‘constructor’ of undefined” error occurs when you attempt to access the constructor
property of a variable that is undefined
. To fix it, perform an undefined
check on the variable before trying to access the constructor
property.
const user = undefined;
// TypeError: Cannot read properties of undefined (reading 'constructor')
const User = user.constructor;
const newUser = new User();
In this example, the user
variable is undefined
, so we get an error when we try to access a property from it. We fix it by checking if the variable is nullish before accessing the constructor
property. We can do this with the optional chaining operator (?.
):
const user = undefined;
// Optional chaining in if statement
if (user?.constructor) {
const User = user?.constructor;
const newUser = new User();
}
Using the optional chaining operator on a variable will return undefined
and prevent the property access if the variable is nullish (null
or undefined
).
We can also use an if
statement to check if the variable is truthy:
const user = undefined;
// Check if 'user' is truthy
if (user && user.constructor) {
const User = user.constructor;
const newUser = new User();
}
Tip
In JavaScript, the constructor
property of an instance object returns a reference to the Object
constructor function that created the object.
let obj1 = {};
obj1.constructor === Object; // -> true
let obj2 = new Object();
obj2.constructor === Object; // -> true
let arr1 = [];
arr1.constructor === Array; // -> true
let arr2 = new Array();
arr2.constructor === Array; // -> true
let num = new Number(3)
num.constructor === Number; // -> true
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.