Question Mark in Variable Name

Viewed 11129

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

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.

Related