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

Laurie Barth
InstructorLaurie Barth
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated a year ago

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.

egghead
egghead
~ an hour ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today