JavaScript: How to remember the difference between "for...in" and "for...of"

JavaScript: How to remember the difference between "for...in" and "for...of"

There was a young programmer in Berlin
Who constructed a for loop with in
She found the effect is
A series of indexes
And swore ne'er to use it again.

Don't use for...in

Here's what happened to our programmer in Berlin:

const cities = ["Berlin", "Prague", "Los Angeles"];
for (const city in cities) {
  console.log(city);
}

// Output ->
// 0
// 1
// 2

The bottom line is that for..in rarely does what we expect it to do or what we need it to do. Instead of trying to remember how it works, just remove it from your toolbox.

Use for...of

Here's how our programmer in Berlin got the results she expected:

const cities = ["Berlin", "Prague", "Los Angeles"];
for (const city of cities) {  // "of", not "in"!
  console.log(city);
}

// Output ->
// Berlin
// Prague
// Los Angeles

Isn't there something I need to remember when looping over objects?

No, just stick with for...of and be explicit about what you're looping over. Consider an object with keys and values:

const cityCatalog = {
  "berlin": {
    name: "Berlin",
    country: "Germany"
  },
  "prague": {
    name: "Prague",
    country: "Czech Republic"
  },
  "losangeles": {
    name: "Los Angeles",
    country: "USA"
  }
};

To loop over the keys, use for...of and Object.keys():

for (const key of Object.keys(cityCatalog)) {
  console.log(key);
  // Need the value? Use cityCatalog[key]
}

// Output ->
// berlin
// prague
// losangeles

To loop over the values, use for...of and Object.values():

for (const value of Object.values(cityCatalog)) {
  console.log(value);
}

// Output ->
// { name: 'Berlin', country: 'Germany' }
// { name: 'Prague', country: 'Czech Republic' }
// { name: 'Los Angeles', country: 'USA' }

Why is it so hard to remember?

If you're like me, then it's hard to remember because most other languages have a for...in that works the way JavaScript's for...of works. Consider C# and Python:

// C# uses "in"
foreach (int num in listOfNums) { ... }
# Python uses "in"
for num in list_of_nums: ...

Summary

  • Don't try to remember the differences; just use for...of.
  • When iterating over objects, use Object.keys() and Object.values() to make your intentions clear.

Photo by AbsolutVision on Unsplash