Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

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

    Laurie BarthLaurie Barth
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Instructor: 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.

    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.

    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.