[SOLVED] Cannot read property 'constructor' of undefined in JS

Last updated on November 20, 2023
[SOLVED] Cannot read property 'constructor' of undefined in JS

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

Every Crazy Thing JavaScript Does

Every Crazy Thing JavaScript Does
Avoid painful bugs and save valuable time with Every Crazy Thing JavaScript Does, a captivating guide to the subtle caveats and lesser-known parts of JavaScript.

See also