Karaja
Karaja

Reputation: 415

What is the Javascript ?. Operator?

I am creating and answering this question for myself because googling "Javascript ?. Operator" provides no useful results.

Questions about the ?. operator to be answered:

  1. What is this operator called?
  2. How does the operator work?
  3. Is this operator supported by typescript?

Upvotes: 1

Views: 76

Answers (1)

Karaja
Karaja

Reputation: 415

  1. This is the Null Propagation Operator (A.K.A. the Existential Operator). Using the operator is called optional or conditional chaining.
  2. This operator is useful when having to access a deeply nested properly value of an object where intermediate properties might be null/undefined.

For example consider this Person Object

let person = {
  name : {
     first : "John",
     last : "Doe"
  },
  age : 31
}

I would access this person's last name as

let lastName = person.name.last;

This is all grand but what if the name object didn't exist? Well the preceding line of code would throw the following error

Uncaught TypeError: Cannot read property 'last' of undefined

To solve this the name property must be checked to make sure it exists. This will turn our simple one liner into the following code

let lastName;
if(person.name){
 lastName = person.name.last;
}

or

let lastName = person && person.name && person.name.last

The first option is just a hassle and the second option isn't swell either. (I personally think the syntax is confusing) For an explanation the second option is checking if person is truthy if it is, it will check if person.name is truthy, if it is person.name.last will be saved into lastName.

So here is the magic of the Null Propagation Operator I can rewrite all of the above snippets as

let lastName = person?.name?.last

Now if person or name is null/undefined lastName will be set to null/undefined and no error will be thrown. For highly nested objects this can save a lot of error checking and lines of code.

  1. This is technically only a proposed ES7 change (https://github.com/tc39/proposal-optional-chaining) but works if you try it out in the console of any chromium browser.

Typescript supports optional chaining as of 3.7 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining

Upvotes: 4

Related Questions