How to Check if an Object has a Nested Property in JavaScript

Check if an Object has a Nested Property Example; In this tutorial you will learn how to check if an Object has a Nested Property in JavaScript.

In Js to check if an object has a nested property, we can use the optional chaining operator – ?.. This operator allows you to read the value of a nested property without throwing an error if the property does not exist on the object, e.g. obj?.a?.b.

Example 1:

const obj = {a: {b: 'test'}};

const value = obj?.a?.b;
console.log(value); // test

if (value !== undefined) {
  //  property exists on object
}

Example 2:

const obj = {};

const value = obj?.a?.b?.c;
console.log(value); // undefined

if (value !== undefined) {
  // property exists on object
}

Example 3:

// Supported in Internet Explorer
const obj = {};

if (obj.a !== undefined && obj.a.b !== undefined && obj.a.b.c !== undefined) {
  // the a.b.c property exists on the object
}