[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();
}
Coding Beauty Assistant logo

Try Coding Beauty AI Assistant for VS Code

Meet the new intelligent assistant: tailored to optimize your work efficiency with lightning-fast code completions, intuitive AI chat + web search, reliable human expert help, and more.

See also