DEV Community

loading...

Discussion on: Don’t pay the for-loop tax

Collapse
martingbrown profile image
Martin G. Brown

While i generally agree with this article's advice, far too often I've seen code like this:

const numbers = [5, 25, 8, 18];
console.log(sum(numbers));
console.log(avg(numbers));
console.log(min(numbers));
console.log(max(numbers));

With loops the fact the code is parsing the array four times would be more obvious. And to my mind easier to fix.

PS: Interesting fact, it is quicker to loop from a large number to zero than zero to the large number. This is because CPUs have a jump if not zero (JNZ) command that eliminates the comparison each iteration of the loop.