Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

246
Views
Is there a cleaner way to check if a deep nested node exists?

Using pure javascript -- no third party / lodash etc.

Given a user looking for the existence of a deep nested node, is there a cleaner way to ensure each parent node exists so as to not return undefined?

Keeping it simple, check that a nested prop has length before performing an action.

The problem is, especially when passing props, at any given node, you could end up with undefined.

Is there a way to avoid checking that each node exists like this:

if( !!Grandparent && !!Grandparent.Parent && !!Grandparent.Parent.child && !!Grandparent.Parent.child.prop3.length){
    // do something
}

Something more like this: (which I know is not correct as any node being undefined hoses the process).

if(!!Grandparent.Parent.child.prop3.length) {
    // do something
}

// OR

if(typeof Grandparent.Parent.child.prop3.length !== "undefined"){
    // do something
}

EX:

   Grandparent: {
        Parent: {
            child: {
                prop1: 'alpha',
                prop2: 'beta',
                prop3: [
                    item: {
                        name: 'first',
                        type: 'string'
                    },
                    item: {
                        name: 'second',
                        type: 'number'
                    }
                ]
            }
        }
    }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As commenters have indicated, modern JavaScript provides the optional chaining operator (?.), which you can use like this (as long as you're not still trying to support IE):

const
  grandparent = getObject(),
  itemsCount = grandparent?.parent?.child?.prop3?.length,
  oops = grandparent?.parent?.child?.length;
console.log(itemsCount ?? "No such property");
console.log(oops ?? "No such property");


function getObject(){
  return {
    parent: {
      child: {
        prop1: 'alpha',
        prop2: 'beta',
        prop3: [
          { item: { name: 'first', type: 'string' }},
          { item: { name: 'second', type: 'number' }}
        ]
      }
    }
  };
}

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!