mercredi 15 janvier 2020

If condition vs loop one item

I was just curious, is it worth to have if condition before looping some array, that in 90% will be array of 1 item? Code example:

const a = [3];
const aLength = a.length;
if(aLength > 1) {
    for(let i = 0; i < aLength; i++) {
        func(i);
    } 
} else {
    func();
}

function func(position = 0) {
  console.log('hi' + position);
}

Aucun commentaire:

Enregistrer un commentaire