JSNov 01, 2014 · 2 min read

Iterating Over Object Values

for...in gives you keys, not values — which trips up anyone iterating arrays for the first time. A comparison of for...in, forEach, for...of, and why plain objects need special treatment.

JavaScript allows us to iterate over objects and arrays with for...in, but it only provides access to the object's keys, not values.

JavaScript
var myArray = ['x', 'y', 'z'];
for(key in myArray) {
    console.log(key);
} //=> 0, 1, 2

If you wanted to access the values, you'd have to access it manually:

JavaScript
for(key in myArray) {
    console.log(myArray[key]);
} //=> x, y, z

Practically, if you wanted to iterate over an array, you might use the forEach method, which gives you access to the key, value, as well as entire array:

JavaScript
myArray.forEach(function(value, key, array){
    console.log(value);
});  //=> x, y, z

For...Of Loops

ES6 allows iteration over array values with for...of loops:
JavaScript
var myArray = ['x', 'y', 'z'];

for(key in myArray) {
    console.log(key);
} //=> 0, 1, 2

for(element of myArray) {
    console.log(element);
} //=> x, y, z

Iterating over Objects

What if you wanted to iterate over an object? In ES5, you could use forEach on Object.keys():
JavaScript
var myObj = {
    'a': 'foo',
    'b': 'bar',
    'c': 'baz'
}

Object.keys(myObj).forEach(function(v, k, a){
    console.log(v); //=> a... b... c...
    console.log(k); //=> 0... 1... 2
});

for...in loops also work on objects, but similar to iterating over arrays you only have direct access to the key, not value:

JavaScript
var myObj = {
    'a': 'foo',
    'b': 'bar',
    'c': 'baz'
}

for(key in myObj) {
    console.log(key);
} //=> a, b, c

For...of and Object Iterators

Out of the box, for...of loops don't work with non-array objects. That's because the for...of loops relies on an internal iterator, something that comes for free with arrays.

If you'd like to use for...of to iterate over an object's values, you can do so after defining it's iterator.