Reputation: 165
why is typeof not checking if a variable is undefined with the below snippets:
if(typeof res.data.data[1].name !== undefined){
//the idea is that if code gets here it means it contains some data
.......
}
with the above check I still get this outcome at the if block
TypeError: Cannot read property 'name' of undefined
Upvotes: 0
Views: 134
Reputation: 2879
It is happening because res.data.data[1]
is undefined itself. I'd suggest expand your condition to something like:
const { data = [] } = res.data;
if (data[1] && typeof data[1].name !== 'undefined') {
// Do somehing
}
Also your check is incorrect as you are comparing typeof result with undefined
while it returns a string, in this case 'undefined'
Upvotes: 0
Reputation: 222582
This could be because of res.data.data is null , just add a null check
if(res.data.data && typeof res.data.data[1].name !== undefined){
Upvotes: 1