DEV Community

Discussion on: Let's loop - for...in vs for...of

Collapse
 
abbadev profile image
Abdulla T • Edited

Nice article. This was a nice deep dive into the differences between both.

As you mentioned above "As it turns out, for...in can handle iterables as well as objects.", so I wanted to comment on this point.

It's been a while for me to use either of these loops, but I always remember that when I had to choose a loop that I remember reading different articles with general advice to avoid the for..in loop if looping over an array. So, I did a 5 minutes quick search (not anywhere near your deep dive) but this Stackoverflow question has different answers on why a for..in loop is not a good idea for arrays. A clear example of this is if you had undefined values in your array at different indexes, a for..in loop will just ignore the empty values. Anyways, this is worth considering but in the end, the point of which loop to use will depend on the app context.

    const arr =[];

    arr[3] = "Value at index 3";

    const temp1Arr = [];
    const temp2Arr = [];

    for (const i of arr) {
        temp1Arr.push(i);
    }

    console.log("temp1Array after a for of loop", temp1Arr);
   // temp1Array after a for of loop [undefined, undefined, undefined, "Value at index 3"]

    for (const i in arr) {
        temp2Arr.push(arr[i]);
    }

    console.log("temp2Array after a for in loop", temp2Arr);
   // temp2Array after a for in loop ["Value at index 3"]