1

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 
}

 
mshwf
  • 7,009
  • 12
  • 59
  • 133
Ben Jonson
  • 565
  • 7
  • 22
  • Its called optional chaining https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining – Rashomon Oct 29 '21 at 10:46

1 Answers1

-1

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
Ran Turner
  • 14,906
  • 5
  • 47
  • 53