Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

80
Visualizações
Single Try Catch instead of multple If statements

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
}
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda