2

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.

5
  • Does this answer your question? Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?
    – xdeepakv
    Commented Oct 8, 2021 at 7: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. Commented Oct 8, 2021 at 7:08
  • This link may be used. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    – xdeepakv
    Commented Oct 8, 2021 at 7:13
  • @xdeepakv No, still looking for professional expertise and pros/cons about the usage. I know how it works ;) Commented Oct 8, 2021 at 7: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
    Commented Oct 8, 2021 at 8:10

1 Answer 1

5

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.