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

1
  • Although some might disagree, you could consider using try/catch. Commented May 14, 2015 at 16:11

1 Answer 1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

I think your original &&s were correct.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.