Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript check if property defined [duplicate]

Tags:

javascript

What is the recommended way to check if an object property like obj.prop.otherprop.another is defined?

if(obj && obj.prop && obj.prop.otherprop && obj.prop.otherprop.another)

this works well, but enough ugly.

like image 837
rrd Avatar asked Feb 15 '13 17:02

rrd


1 Answers

The most efficient way to do it is by checking for obj.prop.otherprop.another in a try{} catch(exception){} block. That would be the fastest if all the remaining exist; else the exception would be handled.

var a = null;
try {
  a = obj.prop.otherprop.another;
} catch(e) {
  obj = obj || {};
  obj.prop = obj.prop || {};
  obj.prop.otherprop = obj.prop.otherprop || {};
  obj.prop.otherprop.another = {};
  a = obj.prop.otherprop.another ;
}
like image 130
jagzviruz Avatar answered Oct 16 '22 06:10

jagzviruz