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

206
Views
What's the best way to use a for-loop in an if/else statement that performs a similar task?

In the code below, even if the if/else statement evaluates to true or false, the doSomething() function is being called. What I was wondering is if there is a way to refactor this code to make it "DRYer." In my actual code, the body of the loop is longer than just a single function being called, so I figure it's worth refactoring.

if (somethingIsTrue) {
    array1.forEach(val => {
        doSomething(val);
    });
} else {
    array2.forEach(val => {
        doSomething(val);
    });
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The conditional operator can be used here. There's probably no need for the anonymous function wrapper either.

(somethingIsTrue ? array1 : array2).forEach(doSomething);
about 4 years ago · Juan Pablo Isaza Report

0

I would isolate the logic into a common function and pass the array to it. The function doesn't need to know which array its iterating over and that logic of deciding which array can be handled outside the function.

let somethingIsTrue = true;
const mArr1 = [1, 2, 3, 4, 5];
const mArr2 = [6, 7, 8, 9, 10];

businessLogic(somethingIsTrue ? mArr1 : mArr2);
somethingIsTrue = !somethingIsTrue;
console.log('---------------------------');
businessLogic(somethingIsTrue ? mArr1 : mArr2);

function businessLogic(mArr) {
  mArr.forEach(val => console.log(val));
}

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!