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

330
Views
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.

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

0

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

about 4 years ago · Juan Pablo Isaza Report

0

Better to execute the loop one time than the length of array so this is the better of your options

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

Because you only execute the conditional one time then..

about 4 years ago · Juan Pablo Isaza Report

0

As the path of processing this code, i get the following
For every item in the array, i must check the condition
Or no the first option, for this condition, i must do this, otherwise, do that to every item.

The first option, is better in performance, but, unless you're working with BigData i don't think this will influence the processing at all as both are simple instructions to be processed.

This of course depends on the number of itens you're looping and on the complexity of the conditional.

If you use a function in the condition, it'll use more memory, so the first option will be better.

If your condition is simples and your items collection not too large, you are free to use any without problems.

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!