Reputation: 5247
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
};
}
Upvotes: 31
Views: 33775
Reputation: 143
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.
Upvotes: 6
Reputation: 3107
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
Upvotes: 35