Morgan Cheng Morgan Cheng - 1 year ago 78
Javascript Question

What's the simplest approach to check existence of deeply-nested object property in JavaScript?

I have to check deeply-nested object property such as

The code I'm currently using is

if (YAHOO && YAHOO.Foo && YAHOO.Foo.Bar && {
// operate on

This works, but looks clumsy.

Is there any better way to check such deeply nested property?

Answer Source

Sometimes it's just easiest to just put a try catch around it and not worry about all the intermediate segments:

try {
    if ( {
        // operate on
} catch(e) {}

or, depending upon how your code works, it might even just be this:

try {
    // operate on
} catch(e) {
    // do whatever you want to do when doesn't exist

In general, javascript developers under-use try/catch. I find that I can often replace 5-10 if statements with a single try/catch around a larger function block and make the code a lot simpler and more readable at the same time. Obviously, when this is appropriate depends upon the particular code, but it's definitely worth considering more often than it usually is.

FYI, if the usual operation is to not throw an exception with the try/catch, it can be a lot faster than a bunch of if statements too.

If you don't want to use the exception handler, you can create a function to test any arbitrary path for you:

function checkPath(base, path) {
    var current = base;
    var components = path.split(".");
    for (var i = 0; i < components.length; i++) {
        if ((typeof current !== "object") || (!current.hasOwnProperty(components[i]))) {
            return false;
        current = current[components[i]];
    return true;

Example usage:

var a = {b: {c: {d: 5}}};
if (checkPath(a, "b.c.d")) {
    // a.b.c.d exists and can be safely accessed
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download