Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

85
Views
Single Try Catch en lugar de múltiples declaraciones If

Mientras programaba en JavaScript, he estado haciendo esto mucho:

 // get element const elem = document.get... // check if element exists if (elem) { // do anything with the element }

Porque, de lo contrario, recibiría errores al intentar actuar sobre ese elemento si no existiera.

Mi pregunta es, ¿debería usar un solo intento de captura para evitar estar siempre comprobando si el elemento existe? Como en este ejemplo:

 // 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"; } } }

En lugar de tener estos if anidados, ¿debería hacer lo siguiente?

 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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!