user10445503
user10445503

Reputation: 165

using typeof to check if a variable is not undefined

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

Answers (2)

Eugene Tsakh
Eugene Tsakh

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

Sajeetharan
Sajeetharan

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

Related Questions