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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With