Become a member
to unlock all features

Level Up!

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


    Loop over an Object with for...in, Object.keys, Object.values, and Object.entries

    Chris AchardChris Achard

    In Javascript, there are several ways you can iterate over an object's keys and values. We'll look at for...in, which will loop over all the keys (though you may need to also use hasOwnProperty). We'll also look at three built in object functions: keys, values, and entries.



    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




    Instructor: If we have an object, we can loop over the object with a for-in statement, because objects are enumerable. That will loop over all the keys in the object. We can print the keys and access the value for each key from the object, which prints all the keys and the values in our object.

    There are two things to watch out for when using for-in, however. First, you'll see I'm declaring the key as a new const. If we didn't have a const or a let there, it would still work, but then the key variable would be creating a new global variable.

    That value would leak outside of the loop, which is probably not what I want to do. Also, a for-in loop will look at all the properties in the prototype chain. That doesn't matter in this case, since we just have a simple object, but you can protect against that by checking if the object has the key as its own property before doing something with that key.

    We could also choose to loop over the object by calling object.keys first, which returns an array of all the keys in the object. We could loop over the key array with forEach, and do something with that key and the value from the object.

    Or we could map over the keys, then create an array, and do something with the resulting array later. If we're just interested in looping over the values from an object, we could use object.values instead.

    Finally, if we know that we want both the keys and values, we can get both at once using object.entries. You can see that each entry is an array, with the first element being the key and the second element being the value.

    We could extract the key and the value from that array, or we could destructure that in the function argument list itself, which gives us a clean way to extract the key and the value for every pair in the object.