Using Objects in For Of Loops

Daniel Herr picture Daniel Herr · Apr 27, 2015 · Viewed 73.1k times · Source

Why isn't is possible to use objects in for of loops? Or is this a browser bug? This code doesn't work in Chrome 42, saying undefined is not a function:

test = { first: "one"}

for(var item of test) {
  console.log(item)
}

Answer

Overv picture Overv · Apr 27, 2015

The for..of loop only supports iterable objects like arrays, not objects.

To iterate over the values of an object, use:

for (var key in test) {
    var item = test[key];
}