0

While programming in JavaScript, I have been doing this alot:

// get element
const elem = document.get...

// check if element exists
if (elem) {
  // do anything with the element
}

Because, otherwise, I would be getting errors when trying to act uppon that element if it didn't exist.

My question is, should I use a single try catch to avoid always be checking if the element exists? Like in this example:

// get element
const elem = document.get...

if (elem) {
  // get parent
  const parent = elem.parentElement;
  if (parent) {
    // get children of parent with class 'center'
    const center_elem = parent.getElementsByClassName...
    if (center_elem) {
      center_elem.style.backgroundColor = "white";
    }
  }
}

Instead of having these nested ifs, should I do the following?

try {
  const elem = document.get...
  const parent = elem.parentElement;
  const center_elem = parent.getElementsByClassName...
  center_elem.style.backgroundColor = "white";
}
catch (e) {
  // ignore the errors because I only wanted the code above to happen when the elements existed anyway
}
Bulent
  • 3,307
  • 1
  • 14
  • 22
Diogo Correia
  • 95
  • 4
  • 10
  • 2
    Does this help? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining – James Sep 22 '21 at 17:35
  • 1
    No, don't use `try`/`catch` that suppresses all exceptions, including those from misspellings etc – Bergi Sep 22 '21 at 17:36

0 Answers0