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:
JavaScript
x
13
13
1
let arr1 = [];
2
let arr2 = [];
3
if(someCond){
4
for(let i=0;i<5;i++){
5
arr1.push(i)
6
}
7
}
8
else{
9
for(let i=0;i<5;i++){
10
arr2.push(i)
11
}
12
}
13
or like this:
JavaScript
1
7
1
let arr1 = [];
2
let arr2 = [];
3
for(let i=0;i<5;i++){
4
if(cond) arr1.push(i)
5
else arr2.push(i)
6
}
7
I think the second option looks shorter, but maybe it’s worse in performance.
Advertisement
Answer
The best is:
JavaScript
1
11
11
1
const arr1 = [];
2
const arr2 = [];
3
const cond = Math.random() > 0.5;
4
const arr = cond ? arr1 : arr2;
5
6
for(let i = 0; i < 5; ++i){
7
arr.push(i);
8
}
9
10
console.log('arr1', arr1);
11
console.log('arr2', arr2);