Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: Prevent Error if Accessing Attributes of Undefined Object

Tags:

javascript

My goal: Test if the attribute of an object is/returns true. However, in some cases, the object is undefined.


This works no problem. The script continues normally.

if(somethingUndefined){ }


However, if I try to access an attribute of an undefined object, this generates an error and stops the script.

if(somethingUndefined.anAttribute){ }


Right now, this is what I'm using to solve the problem:

if(somethingUndefined && somethingUndefined.anAttribute){ }


Is there another way to do that? Maybe a global settings that will return false if the program tries to access an attribute of an undefined object?

like image 404
RainingChain Avatar asked Nov 01 '22 15:11

RainingChain


1 Answers

If you have many if statement like if(somethingUndefined && somethingUndefined.anAttribute){ }, then you could assign an empty object to it when it is undefined.

var somethingUndefined = somethingUndefined || {};

if (somethingUndefined.anAttribute) {

}
like image 158
xdazz Avatar answered Nov 09 '22 13:11

xdazz