Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null checks for elements with optional chaining

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.

like image 473
ivi_does_it Avatar asked May 03 '26 20:05

ivi_does_it


1 Answers

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

like image 73
Chirag Maniar Avatar answered May 05 '26 09:05

Chirag Maniar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!