0

What would be the easiest way to check for undefined, NuLL and "" in this case:

I am receiving an object that can have and of those three states, and it comes in form of:

images[0].url

Images might not exists at all Images might have url property of null Images might have property of ""

I was using if(images[0]), but it covers only existence of [0], not deeper. How can I solve this, without switch statement.

I tried something like this:

   if((object.images[0]) || (object.images[0].url)){

} else {

}

But if the [0] exists and url does not, then I get this. Uncaught TypeError: Cannot read property 'url' of undefined

Amiga500
  • 5,874
  • 10
  • 64
  • 117
  • Although some might disagree, you could consider using `try/catch`. –  May 14 '15 at 16:11

1 Answers1

1

You get this error when object. images[0] does not exist. To avoid this you could have a gradual check like this.

 if(object.images && object.images[0] && object.images[0].url){ 
//do stuff
}
shershen
  • 9,875
  • 11
  • 39
  • 60