For...in Loop vs. For...of Loop

Laurie Barth
InstructorLaurie Barth
Share this video with your friends

Social Share Links

Send Tweet

Arrays can be iterated through using both for...in and for...of, but there are differences. This video shows that for...of accesses the values of each element and for...in accesses the indexes of each element.

Instructor: [00:01] define and array with the elements one, two and three. If we use a for of loop on the array and console log each item, we'll see that they're equivalent to each item in the array. If instead we use a for in loop and console log each item, we'll see that it's equivalent to the index of that array element.

[00:31] In a real world use case, we'd likely start with an object, in this case, obj. Remember that Object.entries() turns an object into its multi-dimensional array representation. If we want to access both the key and value of each sub-array, we'd use for of on Object.entries() result. Here we can see that we can console.log the key and the value in one loop.

[01:19] On the other hand, if we decided not to manipulate the object, we could access the key directly using a for in loop, which is similar to the way that array and disease are treated in our simplified example.