Javascript
JavaScript Fundamentals -- Looping in JavaScript

for ... in Loops

PRO
Outline

The first thing to note with for ... in loops is that they look very similar to for ... of loops. They are not interchangeable, however. When you use a for ... of loop, you get access to each element in the array, one each time through the loop. When you use a for ... in loop on an array, however, you get access to the index of each item in the array. I've found it to be very rare to use this loop on an array, because I don't often need access to just the index of an element in the array.

Unlike the for ... of loop, however, you can use the for ... in loop on an object as well. When you do that, you get access to the attributes, or the keys in the key/value pairs, each time through the loop. This is convenient if you need to log the name of each attribute, or you want to rename an attribute, or you want to do something to all the string values in the object (like uppercase them). I also don't use this very frequently, but there have been times when I've needed to loop over the attributes of an object, and this makes it very convenient.

To read more about the for ... in loop, read this blog post or check out the documentation.

 

I finished! On to the next chapter