0

I am trying to understand these lines of code in a react.js file:

const { search } = useLocation();
const match = search.match(/type=(.*)/);
const type = match?.[1];

First two lines I can understand but I don't understand the conditional used in the last line(type). What does this ?. means in the code

David
  • 208,112
  • 36
  • 198
  • 279
saba
  • 43
  • 7
  • 2
    What you're seeing is called [Optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). – David Jun 07 '23 at 15:51
  • Optional chaining oh thanks @David!! – saba Jun 07 '23 at 15:53

1 Answers1

1

This is not related to React or rendering. It is a JavaScript feature called "Optional chaining":

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

The optional chaining (?.) operator accesses an object's property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.

So for example, if the string does not match the regular expression, then match will be undefined. So match[1] would cause an error.

% node
Welcome to Node.js v18.16.0.
Type ".help" for more information.
> const search = "test"
undefined
> const match = search.match(/type=(.*)/);
undefined
> match[1]
Uncaught TypeError: Cannot read properties of null (reading '1')
> match?.[1]
undefined
Wodin
  • 3,243
  • 1
  • 26
  • 55