I met in code condition line like this someObject.arrParam?.length. What syntax is that? How does that question mark thing's called? I know an optional operator which used for parameters in functions. Is that a variation of usage of it? Never met before.
-
Perhaps => Optional ChainingAlways Helping– Always Helping2020-09-03 11:26:34 +00:00Commented Sep 3, 2020 at 11:26
-
1Duplicate of Optional Chaining in JavaScript. See What does this symbol mean in JavaScript? and the documentation on MDN about expressions and operators and statements.Sebastian Simon– Sebastian Simon2020-09-03 15:15:47 +00:00Commented Sep 3, 2020 at 15:15
3 Answers
This is called Optional Chaining in JavaScript. It allows to drill down on objects without raising null exception.
Eg: Try running the below code snippet, then uncomment the line and run it to understand a working example.
let employeeA ={ name: "Dane", address : { city:"London"}}
let employeeB ={ name: "John"}
console.log(employeeA.address.city)
// console.log(employeeB.address.city) <---- this will raise an error
console.log(employeeB.address?.city) // <--- this wont
This was introduced as new feature in the latest ESNext iterations.
NodeJS Support : https://node.green/#ES2020-features-optional-chaining-operator-----
Current Browser Support : https://caniuse.com/#feat=mdn-javascript_operators_optional_chaining
More Details here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
Comments
That is called Optional Chaining (or conditional chaining) which basically will evaluate the whole expression as undefined if arrParam is undefined or null.
Comments
It's called "Conditional (ternary) operator".
result=condition?ifTrue:ifFalse
In x=(y>10)?100:1, if y>10, x is set to 100, else, x is set to 1.
Equivalent to:
if(y>10) x=100;
else x= 1;