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

Time:04-30

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);
    });
}

CodePudding user response:

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

(somethingIsTrue ? array1 : array2).forEach(doSomething);

CodePudding user response:

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];

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

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

  • Related