Clue Mediator

Uncaught TypeError: Cannot read property of undefined

šŸ“…January 17, 2022
šŸ—JavaScript

In this article, we will show you how to resolve a JavaScript error `Uncaught TypeError: Cannot read property of undefined`. Undefined means that a variable has been declared but has not been assigned a value.

Checkout more articles on JavaScript

Error:

function myFunc(x) {
  console.log(x.y);
}

var myVar;
myFunc(myVar);

// Uncaught TypeError: Cannot read properties of undefined (reading 'y')

Solution 1:

When such an error is encountered, make sure that the variable causing the error is assigned a value.

function myFunc(x) {
  console.log(x.y);
}

var myVar = {
  y: 'myProp'
};
myFunc(myVar);

// myProp

Solution 2:

If you use JavaScript according to ECMAScript 2020 or later, see optional chaining.
Use it like this: `obj?.a?.lot?.of?.properties`

function myFunc(x) {
  console.log(x?.y);
}

var myVar;
myFunc(myVar);

Solution 3:

Alternatively, an `if` check should be added before dealing with variables.

if (myVar !== undefined) {
    ...
}
if (typeof(myVar) !== 'undefined') {
    ...
}

Letā€™s update the previous example to include an `if` check.

function myFunc(x) {
  if (x !== undefined) {
    console.log(x.y);
  }
}

var myVar;
myFunc(myVar);

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! šŸ™‚