Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question mark before dot in javascript / react [duplicate]

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?

like image 521
Robert Tirta Avatar asked May 17 '20 05:05

Robert Tirta


People also ask

What does question mark and dot mean in react?

JavaScript question mark dot is called optional chaining operator. It allows reading the value of a property located in a Nested object.

What is the use of question mark in react JS?

“Question mark” or “conditional” operator in JavaScript is a ternary operator that has three operands. The expression consists of three operands: the condition, value if true and value if false.

What is double question mark in JavaScript?

The JavaScript double question mark (??) operator is called the nullish coalescing operator and it provides a default value when a variable or an expression evaluates to null or undefined.

What does a question mark mean in react native?

The question mark ? is an alternative to an if statement best used in the case where one of two values will be assigned to a variable based on a conditional statement.


1 Answers

That's optional chaining: MDN

The optional chaining operator ?. permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid. The ?. operator functions similarly to 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.

like image 78
NULL SWEΔT Avatar answered Sep 20 '22 19:09

NULL SWEΔT