Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Thanks

>Solution :

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 });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading