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

177
Views
Check object variable exists when using object destructuring

I have a 'getData' function which gets passed a 'data' variable. Inside the function I'm trying to access an object 'data.someObject' which may or may not exist because it comes from an outside library.

What is the best approach to check if it does exist before trying to use it? Also see I'm using object destructuring here aswell.

const getData = (data) => {
    const { name, age } = data.someObject; // someObject may or may not exist
    console.log(name, age);
}

I thought doing this might work:

const { name, age } = data.someObject || {};

But I wasn't sure if that would throw an error.

Thanks

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Personally I would put an if statement:

const getData = (data) => {
  if (data.someObject == null) {
    // Here you can return, throw an error or do anything else you might need
  }
  const { name, age } = data.someObject; // someObject may or may not exist
  console.log(name, age);
}
about 4 years ago · Juan Pablo Isaza Report

0

You can use || & if required provide default values while destructuring.

function print(user) {
  const { fname = "Anonymous", lname = "Panda" } = user.fullname || {};

  console.log(`Hello ${fname} ${lname}`);
}

print({ fullname: { fname: "John", lname: "Doe" } });
print({});
print({ fullname: null });

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!