admin管理员组

文章数量:1398999

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?

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?

Share Improve this question asked Sep 20, 2013 at 12:56 Adam HalaszAdam Halasz 58.4k67 gold badges153 silver badges216 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 10

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.

本文标签: Javascript Checking object child array length even if object is not definedStack Overflow