Test for existence of nested JavaScript object key in JavaScript

Testing for the existence of nested JavaScript object keys is a common requirement when working with complex data structures. This prevents errors when accessing deeply nested properties that may not exist.

The Problem

Accessing nested properties directly can throw errors if intermediate keys don't exist:

let test = {};
// This would throw an error:
// console.log(test.level1.level2.level3); // TypeError: Cannot read property 'level2' of undefined

Using a Custom Function

We can create a function that safely checks each level of nesting:

const checkNested = function(obj = {}){
    const args = Array.prototype.slice.call(arguments, 1);
    for (let i = 0; i < args.length; i++) {
        if (!obj || !obj.hasOwnProperty(args[i])) {
            return false;
        }
        obj = obj[args[i]];
    }
    return true;
}

let test = {
    level1:{
        level2:{
            level3:'level3'
        }
    }
};

console.log(checkNested(test, 'level1', 'level2', 'level3'));
console.log(checkNested(test, 'level1', 'level2', 'foo'));
true
false

Modern Approach with Optional Chaining

ES2020 introduced optional chaining (?.) for safer property access:

let test = {
    level1: {
        level2: {
            level3: 'level3'
        }
    }
};

// Safe access with optional chaining
console.log(test?.level1?.level2?.level3 !== undefined); // true
console.log(test?.level1?.level2?.foo !== undefined);    // false

// Direct value access
console.log(test?.level1?.level2?.level3);  // 'level3'
console.log(test?.level1?.level2?.foo);     // undefined
true
false
level3
undefined

Using try-catch Approach

Another method is to wrap property access in a try-catch block:

function safeAccess(obj, path) {
    try {
        return eval(`obj.${path}`) !== undefined;
    } catch (e) {
        return false;
    }
}

let test = {
    level1: {
        level2: {
            level3: 'level3'
        }
    }
};

console.log(safeAccess(test, 'level1.level2.level3')); // true
console.log(safeAccess(test, 'level1.level2.foo'));    // false
true
false

Comparison

Method ES Version Performance Readability
Custom Function ES5+ Good Moderate
Optional Chaining ES2020+ Best Excellent
try-catch ES5+ Poor Good

Conclusion

Use optional chaining (?.) for modern JavaScript environments as it's the most readable and performant. For older environments, the custom function approach provides reliable nested key checking.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements