0

It's common in React that an element is rendered before all its variables are defined, with final rendering being correct. To prevent fatal errors we usually use the ? operator as suggested in the response to Question by coding:

const property1 = object?.property1

rather than:

const property1 = object.property1 or const { property1 } = object

This approach doesn't work when the object is an array of objects, for instance if I want to preempt a fatal error in react while my array is undefined, I can't use:

const property1 = array?[0]?.property1

since it is syntactically incorrect (should it be?), so I am using:

 `const property1 = array && array[0]?.property1`

Is that the correct way?

Daniel Beck corrected an error in my original question, that is now fixed indicating that an alternative way to handle this situation would be:

const uid = array ? array[0].uid : undefined
1
  • Thanks for your comment, I didn't check it, since I was quoting from somebody else, I should have! I will edit it and change the quote to you. Commented Feb 12, 2022 at 16:39

1 Answer 1

1

You can use Array.isArray() method to determine whether the passed value is an Array or not.

Working Demo :

let obj = {
    property1: 'alpha' 
};

const property1 = Array.isArray(obj) ? obj[0]?.property1 : obj.property1;

console.log(property1);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.