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.
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