-3

I'm using react-hook-form and I came across ?. operator. What does it mean? Here is some context on how it's used

<span>{errors?.name?.message}</span>

Where errors is destructured from useForm() like so

const { register, handleSubmit, formState: { errors } } = useForm();

Here is a full form input to paint a clearer picture

<input 
   type="text" 
   id='name' 
   name='name'
   {...register('name', {
      required: {
        value: true,
        message: 'Name cannot be empty'
      }
    })}
    placeholder='John Doe' 
    className='px-6 w-full rounded-md py-2 text-gray-700 focus:outline-none' 
                    
   />
<span>{errors?.name?.message}</span>
  • It is the [optional chaining operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining). – Unmitigated Oct 20 '21 at 21:24
  • 2
    Does this answer your question? [Optional Chaining in JavaScript](https://stackoverflow.com/questions/26183944/optional-chaining-in-javascript) – Sören Weber Oct 20 '21 at 21:25
  • it means the property is `optional` or can potentially be `undefined` – German Oct 20 '21 at 21:32

1 Answers1

0

?. is the optional chaining operator. Here is the MDN Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining

For example if you run the below code, you will face an error

a = {}
console.log(a.b.c)

Uncaught TypeError: Cannot read property 'c' of undefined

But if you do not want to add a try-catch, but it is acceptable for that value to be absent, then you can do the following

a = {}
console.log(a.b?.c)

This will result in undefined to be printed to the console. The error in accessing c is silently handled.

Ronnie
  • 512
  • 5
  • 12