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 Chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) – Always Helping Sep 03 '20 at 11:26
-
1Duplicate of [Optional Chaining in JavaScript](https://stackoverflow.com/questions/26183944/optional-chaining-in-javascript). See [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212) and the documentation on MDN about [expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators) and [statements](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements). – Sebastian Simon Sep 03 '20 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

- 4,818
- 1
- 27
- 38
That is called Optional Chaining (or conditional chaining) which basically will evaluate the whole expression as undefined
if arrParam
is undefined
or null
.

- 5,846
- 3
- 25
- 37
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;

- 2,760
- 2
- 11
- 23