Following the series of questions and answers of the same theme
We will clarify its equivalent in Javascript:
What does it mean?
The meaning of the error message "Uncaught TypeError: Can not read property 'XXX' of undefined" is:
Error TypeError not captured: I can not read property 'XXX' of undefined
.
And it means that we are trying to access a property (attribute or function) of an identifier that is not defined.
In the example of the question the error occurs because we have two variables, obj1 and obj2, where a obj1 has not been assigned any value, it is undefined . If obj1 were worth null
, the error would be similar.
How to fix it?
The way to solve it is to look in our code for the attribute XXX
that you try to access (or define) and then see why the parent object is null
or undefined
.
Typical reasons are usually:
-
Try to access a variable modified by asynchronous code (the response to an AJAX call or an event such as a mouse click or the pressing of a key) before it has assigned a value to said variable.
-
Assume that a function always returns a value other than null
or undefined
: for example, if this query returns a list with 2 elements, but we are trying to access a nonexistent third element:
let myDivs = document.getElementsByClass('myDiv');
let text=myDivs[2].innerText;
// Uncaught TypeError: Cannot read property 'innerText' of undefined