Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Checking object child array length even if object is not defined

I would like to display some content only if an object's child array has elements in it. But sometimes the object itself is not defined so doing this fails if object or object.child is not present at the scope:

if(object.child.length){
    alert('hello world');
}

Which results in:

Uncaught ReferenceError: object is not defined

So I have to add two additional if conditions to check if the object and it's child is defined or not:

if(typeof object !== 'undefined'){
    if(typeof object.child !== 'undefined'){
        if(object.child.length){
            alert('hello world');
        }
    }
}

Writing a function around this is problematic too:

function isset(value){ ... }
if(isset(object.child.length)({ ... } // <-- still raises error that object is not defined

Is there a cleaner, shorter way to do this?

like image 788
Adam Halasz Avatar asked Dec 25 '22 20:12

Adam Halasz


1 Answers

You can put a guard on:

if(object && object.child && object.child.length){

The above defends against object and object.child being undefined or null (or any other falsey value); it works because all non-null object references are truthy, so you can avoid the verbose typeof object !== "undefined" form. You may not need both of the guards above, if you know for sure that object.child will exist if object does. But having both is harmless.

It's worth noting that this is useful even when retrieving values, not just for testing them. For instance, suppose you have (or may not have!) object.foo, which contains a value you want to use.

var f = object && object.foo;

If object is falsey (undefined or null are the typical cases), then f will receive that falsey value (undefined or null). If object is truthy, f will receive the value of object.foo.

|| is curiously powerful in a similar way.

like image 178
T.J. Crowder Avatar answered Dec 28 '22 11:12

T.J. Crowder