Uncaught TypeError: Cannot read property of undefined
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:
1 2 3 4 5 6 7 8 | 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.
1 2 3 4 5 6 7 8 9 10 | 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
1 2 3 4 5 6 | function myFunc(x) { console.log(x?.y); } var myVar; myFunc(myVar); |
Solution 3:
Alternatively, an if
check should be added before dealing with variables.
1 2 3 4 5 6 | if (myVar !== undefined) { ... } if (typeof(myVar) !== 'undefined') { ... } |
Let’s update the previous example to include an if
check.
1 2 3 4 5 6 7 8 | 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..!! 🙂