21

In React custom hook we are returning ordernumber in the below way what does question mark after the variable receipt?.order?.id means in react

export const useTest = props => {
  ...
  return {
    orderTestNumber: receipt?.test?.id
  };
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Arav
  • 4,957
  • 23
  • 77
  • 123
  • 5
    It's known as the "optional chaining operator". This is how it works; in case you are referencing a deeply nested property, not all the references will be validated. Therefore, in case of a missing reference, it does not throw an error, instead, it returns undefined. – elonaire Aug 20 '20 at 05:00
  • 5
    This is a regular javascript operator, nothing specific to react or react hooks, BTW. – Drew Reese Aug 20 '20 at 05:19

2 Answers2

25

its called Optional chaining (?.)

The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

VaibhavJoshi
  • 355
  • 2
  • 15
Jay
  • 2,826
  • 2
  • 13
  • 28
2

Just one thing to mention: You can not use the "Optional chaining operator (?.)" on a non-declared root object, but with an undefined root object. For instance, if you are trying to access the properties of a non-declared "obj" object, you will get an error:

console.log(obj?.someProperty);  
**obj is not defined**

But if you have already declared your object and trying to access the property which is Null or undefined, you will get an undefined result :

const obj = {}
console.log(obj?.someProperty);
**undefined**

OCO is handy when you are working with the objects which are dynamically creating properties/assigning values to the properties, and you are not sure about the validation of the property you are trying to access/manipulate.

Zarik
  • 65
  • 6