1

My code is getting really quite polluted with:

if( typeof( objectVar ) === 'object' && objectVar !== 'null' )
  if( typeof( objectVar.other ) === 'object' && objectVar.other !== 'null' )
     // OK, objectVar.other is an object, yay!
   }
 }

This is a little ridiculous. I am after a function that reads like this:

isProperObject( objectVar.other );

Considering that if objectVar is not defined, this will actually fail miserably, maybe I should do instead:

isProperObject( 'objectVar.other' );

Then the function could eval() it. But no! It cannot do that, because isProperObject() would be in a different scope, one without objectVar.

So, it could be:

isProperObject( objectVar, 'other' )

OK this could work. Is there a function like this that is actually commonly used?

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Merc
  • 16,277
  • 18
  • 79
  • 122
  • You can create one of your own, look through the props and go on, once you find a part undefined return false. – PSL Oct 12 '13 at 00:49
  • 1
    possible duplicate of [Check if object member exists in nested object](http://stackoverflow.com/questions/4676223/check-if-object-member-exists-in-nested-object) – Cᴏʀʏ Oct 12 '13 at 00:52

2 Answers2

1

Your checks are needlessly verbose. You can do this instead:

if (objectVar != null && objectVar.other != null) {
   // OK, objectVar.other is an object, yay!
}

This will check for both null and undefined, and so gives you the safety you need.

Or if you really need .other to be an object:

if (objectVar && typeof objectVar.other === "object") {
   // OK, objectVar.other is an object, yay!
}

Also, you should have been testing for:

!== null

instead of:

!== 'null'

A different, novel approach is this:

if((objectVar || {}).other != null) {
user2736012
  • 3,543
  • 16
  • 13
0

Move to a "higher level" of programming and initialize values to a null or empty object.

You should be working with top- and intermediate-level objects which are initialized to usable values, and you thus know to exist. Only the "leaf" objects should potentially be in empty/ null state.

For example, instead of:

var dialogTitle;
var dialogId;
var dialogElement;

Prefer to build a valid container object, in an "empty" state.

var dialog = {
    title: null,
    id: null,
    element: null
};

You can also use if (dialog.id != null) or, when you're not expecting false or 0 values, if (dialog.id).

Thomas W
  • 13,940
  • 4
  • 58
  • 76