Often finding the conditional syntax like array followed by "?" and "." and element, example - edges[0]?.node. How to interpret the following code?
export default function Index({ allPosts: { edges }, preview }) {
const heroPost = edges[0]?.node;
const morePosts = edges.slice(1);
....// rest of the code
}
This is the optional chaining operator (?.) which enables you to read the value of a property located deep inside a chain of connected objects without having to check that each reference in the chain is valid in each reference protecting you from getting the error Uncaught TypeError: Cannot read properties of undefined
This operator is like the . chaining operator, except that instead of causing an error if a reference is considered nullish (which means null or undefined), the expression short-circuits with a return value of undefined (hence, not throwing an exception).
const person = {
name: 'John',
dog: {
name: 'cc'
}
};
const dogName = person.dog?.name;
console.log(dogName);
console.log(person.cat?.name?.prop); // undefined instead of throwing an error