admin管理员组

文章数量:1168540

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
  };
}

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
  };
}
Share Improve this question edited Aug 20, 2020 at 5:19 Drew Reese 202k17 gold badges231 silver badges265 bronze badges asked Aug 20, 2020 at 4:50 AravArav 5,24723 gold badges85 silver badges127 bronze badges 2
  • 9 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 Commented Aug 20, 2020 at 5:00
  • 8 This is a regular javascript operator, nothing specific to react or react hooks, BTW. – Drew Reese Commented Aug 20, 2020 at 5:19
Add a comment  | 

2 Answers 2

Reset to default 35

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

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.

本文标签: javascriptQuestion Mark in Variable NameStack Overflow