Skip to content
Advertisement

What is the best option, a loop inside a conditional or a conditional inside a loop?

Seems obvious, but let’s say we have 2 arrays and I want to push some objects inside if certain condition is true. Generally speaking, it would be better like this:

let arr1 = [];
let arr2 = [];
if(someCond){
  for(let i=0;i<5;i++){
    arr1.push(i)
  }
}
else{
  for(let i=0;i<5;i++){
    arr2.push(i)
  }
}

or like this:

let arr1 = [];
let arr2 = [];
for(let i=0;i<5;i++){
  if(cond) arr1.push(i)
  else arr2.push(i)
}

I think the second option looks shorter, but maybe it’s worse in performance.

Advertisement

Answer

The best is:

const arr1 = [];
const arr2 = [];
const cond = Math.random() > 0.5;
const arr = cond ? arr1 : arr2;

for(let i = 0; i < 5; ++i){
  arr.push(i);
}

console.log('arr1', arr1);
console.log('arr2', arr2);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement