0

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 ?

  • You only need to use it on nullable properties, or properties that could potentially be `null` or `undefined`. – kelsny Sep 15 '22 at 16:22
  • The optional chaining `?.` stops the evaluation if the value before `?.` is undefined or null and returns undefined. – norbekoff Sep 15 '22 at 16:24
  • Depending on the context I would personally normalize the data structure, such that you can navigate though it without optional chaining. This allows you to completely remove optional chaining from the actual logic. – 3limin4t0r Sep 15 '22 at 16:49

1 Answers1

0

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!');
}
jfhr
  • 687
  • 5
  • 13