1

Is it good practice to do null checks with optional chaining like the following example?

document.querySelector('.foo')?.classList.add('bar');

In many codebases I see this:

let el = document.querySelector('.foo');

if(el){
 el.classList.add('bar');
}

I think chaining is much cleaner and silent failures are happening in both cases. I'm aware of the browser support.

ivi_does_it
  • 155
  • 1
  • 8
  • Does this answer your question? [Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?](https://stackoverflow.com/questions/6613952/is-there-a-null-coalescing-elvis-operator-or-safe-navigation-operator-in-javas) – xdeepakv Oct 08 '21 at 07:05
  • Thank you, but not really. I'm asking about good and bad practice, about pros and cons of using the optional chaining with html element. – ivi_does_it Oct 08 '21 at 07:08
  • This link may be used. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining – xdeepakv Oct 08 '21 at 07:13
  • @xdeepakv No, still looking for professional expertise and pros/cons about the usage. I know how it works ;) – ivi_does_it Oct 08 '21 at 07:47
  • It is an absolutely fine practice to do. The code is clean and tidy. Some people might say that the second example is better readable, however using null checks with optional chaining is very often used nowadays. The advantage is that the code is shorter, the disadvantage is that the code could be a bit less good readable. – AztecCodes Oct 08 '21 at 08:10

1 Answers1

4

Yes, Optional Chaining is really tidy and neat way not only for Null verification but undefined as well with JS.

It allows you to make your code readable as well as less cluttered.

I'll suggest to deep more into Optional Chaining to use it's fantastic features.

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

Chirag Maniar
  • 316
  • 1
  • 5