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

150
Views
multiple if statements into better structure

list.forEach(el, i) {
  var isTrue = true;
  if (isTrue && i == 0) {
    ary[0] = obj.innerText;
  }
  if (isTrue && i == 1) {
    ary[0] = obj.closest(list[0]).innerText;
    ary[1] = obj.innerText;
  }
  if (isTrue && i == 2) {
    ary[0] = obj.closest(list[0]).innerText;
    ary[1] = obj.closest(list[1]).innerText;
    ary[2] = obj.innerText;
  }
  //same pattern continues up to dozens of if statements
})

Hi, I'm new to JS programming. list contains css selectors. obj is DOM element. How can I improve this code?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

All the if statements look superfluous and repetitive - why not just do it all at once? Extract all .textContent from the matching elements, then put the obj.textContent at the end.

const ary = Array.from(
  { length: i - 1 },
  (_, i) => obj.closest(list[i]).textContent
).concat(obj.textContent);

You almost certainly want .textContent, not .innerText.

If the list may not contain the same number of elements as the number of i conditions you have, just slice the array to the desired length before concating on the final obj.textContent.

about 4 years ago · Juan Pablo Isaza Report

0

Given the value of isTrue doesn't change, the body can be:

ary[i] = obj.textContent;
while (i--) {
  ary[i] = obj.closest(list[i]).textContent;
}

You likely don't need the forEach loop either, just initialise i to ary.length - 1.

about 4 years ago · Juan Pablo Isaza Report
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!