DEV Community

Discussion on: Which types of loops are most popular in the programming languages you use?

Collapse
 
mkenzo_8 profile image
mkenzo_8

Lately, I am liking this way of writing fors in JavaScript:

for(const item of array){
   console.log(item)
}

But I have always used the 'indexed' version:

for(let i = 0;i<array.length;i++){
   console.log(array[i]);
}

There are other ways (forEach for example) but as I know they are usually 'slower' so I always use for :)

Collapse
 
jamesthomson profile image
James Thomson

There are other ways (forEach for example) but as I know they are usually 'slower' so I always use for :)

I think that depends on how much data you're processing. If it's a massive amount, then you may notice it to be a bit slower, but generally the discrepancy is so minimal that it's inconsequential. v8 is actually greatly optimised to use forEach. This is a great talk on the subject by Mathias Bynens: youtube.com/watch?v=m9cTaYI95Zc

So, IMO, it's a far nicer developer experience to use forEach or for of/in in certain cases.