Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent getting error if variable is undefined?

Tags:

javascript

I need to replace imagesrc with the value stored in this object. However when I run:

if(data['results'][res]['entities']['media']["0"]["media_url"]) {
    imagesrc = data['results'][res]['entities']['media']["0"]["media_url"];
}

I get the error:

Cannot read property '0' of undefined

How can I run my condition so that I don't get errors if something is undefined?

like image 493
lisovaccaro Avatar asked Jan 18 '12 19:01

lisovaccaro


2 Answers

if (data['results'][res]['entities']['media']["0"] == undefined
    || data['results'][res]['entities']['media']["0"] == null) {

    ...
}
like image 52
Web User Avatar answered Oct 14 '22 09:10

Web User


you can place your code inside a try catch block and examin error message.

like image 36
Arian Avatar answered Oct 14 '22 10:10

Arian