The following code fails:
let obj1,obj2;
obj2 = {
atributo: 'texto'
};
console.log(obj1.atributo);
Showing in console the message:
Uncaught TypeError: Cannot read properties of undefined (reading 'attribute')
In Firefox (v96) the message is:
Uncaught TypeError: obj1 is undefined
What does it mean and how can I fix it?
Based on the error
This error is very common you are trying to access an element that does not exist or its value is undefined
The error means you can't access that property , but why?
In the example you posted
obj1
it is declared but not used, let's see the data type that the test throws usHow to solve it?
For this error the value of the variables must be null or undefined , what you can do is the following:
Following the series of questions and answers on the same topic
Let's clarify its equivalent in Javascript:
What does it mean?
The meaning of the error message "Uncaught TypeError: Cannot read property 'XXX' of undefined" is:
And it means that we are trying to access a property (attribute or function) of an identifier that is not defined.
In the example in the question the error occurs because we have two variables, obj1 and obj2, where obj1 has not been assigned a value, it is undefined . If obj1 were equal
null
, the error would be similar.How to solve it?
The way to fix this is to look in our code for the attribute
XXX
we're trying to access (or set) and then see why the parent object isnull
orundefined
.Typical reasons are usually:
Attempting to access a variable modified by asynchronous code (the response to an AJAX call or an event such as a mouse click or keystroke) before it has assigned a value to that variable.
Assuming that a function always returns a value other than
null
orundefined
: for example, if this query returns a list with 2 elements, but we are trying to access a non-existent third element: