Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

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

7 months ago · Juan Pablo Isaza
1 answers
Answer question

0

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

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs