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
- How to generate a Unique ID in JavaScript
- Object doesnāt support property or method āremoveā in IE
- Trim string from the dynamic object in JavaScript
- Remove a property from an object in 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..!! š