6

My understanding is that for...in loops are designed to iterate over objects in Javascript. See this post and this post.

Take the following example. This returns 'Uncaught TypeError: items is not iterable' in my console.

var text = {
  name: "Coptic",
  ranges: [[994, 1008], [11392, 11508], [11513, 11520]],
  direction: "ltr",
  year: -200,
  living: false,
  link: "https://en.wikipedia.org/wiki/Coptic_alphabet"
};

function dominantDirection(items) {
  for (let item of items) {
    if (item.direction === 'ltr') {
      return 'ltr';
    } else {
      return 'rtl';
    }
  }
}

console.log(dominantDirection(text));

If I wrap the object in an array[] it works fine. However my second example works as expected.

var object1 = {a: 1, b: 2, c: 3};
var string1 = "";

function loopObj() {
  for (var property1 in object1) {
    console.log(string1 = string1 + object1[property1]);
  }
}

console.log(loopObj());

Why does the first example require an array and the second does not?

CRice
  • 29,968
  • 4
  • 57
  • 70
London804
  • 1,072
  • 1
  • 22
  • 47
  • `text` is not an array for example! – Ele Jul 17 '18 at 20:16
  • 3
    Your first code sample uses `for ... of` not `for ... in`. – Pointy Jul 17 '18 at 20:16
  • Both snippets are doing something completely different. The first is looping over a collection of objects and returning immediately after checking the direction of the first object in the collection. The second snippet is iterating over every property of the passed in object. – Marie Jul 17 '18 at 20:18
  • In your first example, you don't have to iterate through the `text` object to retrieve the direction (you are basically doing two levels of iteration). Simply access the direction via `items.direction` is sufficient. – Terry Jul 17 '18 at 20:19
  • @Pointy wow, I feel silly. Thank you! – London804 Jul 17 '18 at 20:21

1 Answers1

9

In your first example you used for..of which cannot be used on objects but on strings and arrays. To iterate an object either use for..in construct or you get the keys of the object into an array by using Object.keys().

Example using Object.keys():

const text = {
  name: "Coptic",
  ranges: [[994, 1008], [11392, 11508], [11513, 11520]],
  direction: "ltr",
  year: -200,
  living: false,
  link: "https://en.wikipedia.org/wiki/Coptic_alphabet"
};

for (let key of Object.keys(text)) {
  
  console.log(`${key}: ${text[key]}`);
}

Or you could also use the new Object.entries() to get the key and value like below:

const text = {
  name: "Coptic",
  ranges: [[994, 1008], [11392, 11508], [11513, 11520]],
  direction: "ltr",
  year: -200,
  living: false,
  link: "https://en.wikipedia.org/wiki/Coptic_alphabet"
};

for (let [key, value] of Object.entries(text)) {
  
  console.log(`${key}: ${value}`);
}
codejockie
  • 9,020
  • 4
  • 40
  • 46