Question mark before dot in javascript / react

ReactjsReact Native

Reactjs Problem Overview


I know what ternary operator is in React.

When I'm developing react native app I encounter this kind of syntax that is covered by my eslint as unexpected token

ESLint: Parsing error: Unexpected token .

It goes like this:

const routeName = route.state?.routes[route.state.index]?.name ?? INITIAL_ROUTE_NAME;

What does that mean? It uses null coalescing operator in the end, however I can't understand what does the question mark do before a dot.

I know it is a correct syntax because it is a template from expo and they're very popular in react-native development community.

Can anyone help me explain?

Reactjs Solutions


Solution 1 - Reactjs

That's optional chaining: MDN

> The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid. > > The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist. > > This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobert TirtaView Question on Stackoverflow
Solution 1 - ReactjsNULL SWEΔTView Answer on Stackoverflow