It is really necessary to put the ? operator on every attribute of an optional chaining?

Viewed 35

I have been working using optional chaining, but it looks like its enough by putting the ? operator on the penultime attribute to check the entire chain, what you think guys?

In order to check the entire chain would be enough by using the optional chaining like this: data.attr1.attr2?.attr3, or do i still need to put the ? operator on every attribute like this: data?.attr1?.attr2?.attr3 ?

1 Answers

If every part of the chain could independently be null or undefined, then you need to put the ?. operator on every part to avoid a TypeError.

Your example of data.attr1.attr2?.attr3 throws a TypeError if either data or data.attr1 are null or undefined. It returns undefined if data.attr1 is set but data.attr1.attr2 is not.

Try it out yourself:

var data = undefined;
try {
  console.log(data.attr1.attr2?.attr3);
} catch (e) {
  console.log('error!');
}

data = { attr1: undefined }
try {
  console.log(data.attr1.attr2?.attr3);
} catch (e) {
  console.log('error!');
}

data = { attr1: { attr2: undefined } }
try {
  console.log(data.attr1.attr2?.attr3);
} catch (e) {
  console.log('error!');
}

Related