ivi_does_it
ivi_does_it

Reputation: 395

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.

Upvotes: 2

Views: 1490

Answers (1)

Chirag Maniar
Chirag Maniar

Reputation: 346

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

Upvotes: 5

Related Questions