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
2 Answers
Reset to default 35its 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
版权声明:本文标题:javascript - Question Mark in Variable Name - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737588164a1997791.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论