Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 156 Β· Control Flow

for...of and for...in

Loop over arrays, strings, Maps and Sets with for...of, and over object keys with for...in. Learn the difference and the pitfalls of each.

The classic for loop gives you a counter, and you use it to fetch each item: items[i]. Most of the time, though, you don't care about the counter. You just want each item, one after another. Managing i, the condition and the update is extra work and an extra chance for an off-by-one bug.

JavaScript has two shorter loops for walking through collections. for...of gives you the values of anything iterable: arrays, strings, Maps, Sets and more. for...in gives you the keys (property names) of an object. Their names look alike, which makes them easy to mix up, so this lesson covers both side by side, along with the traps that catch people.

for...of: each value in turn

The syntax reads almost like English: "for each fruit of fruits".

JavaScript
for (const item of collection) {
  // item is the next value
}

On each iteration, the variable receives the next value. When the values run out, the loop ends. There's no counter, no condition and no way to read past the end.

JS for...of with an array

Press Run (or Ctrl + Enter) to see the console output here.

No output.

You can use const here, even though the variable holds a different value each time. Each iteration creates a fresh binding, and you never reassign it within an iteration. Use let only if you need to change the variable inside the body.

Strings, Maps and Sets

for...of works with any iterable: any value that knows how to hand out its items one by one. Arrays are iterable, and so are strings, Maps, Sets, and a few other built-in types.

JS Other iterables

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The [product, count] syntax is destructuring: it unpacks each two-item pair into two variables. You'll study it properly in Destructuring; for now, just read it as "name the two parts".

Strings and emoji. for...of walks through a string by Unicode code point, so an emoji such as πŸ˜€ comes out as one item. Indexing with str[i] would split it into two meaningless halves. That makes for...of the safer way to process text character by character.

Getting the index too

Sometimes you want the value and its position. Arrays have an entries() method that produces [index, value] pairs, which you can destructure:

JS Index and value

Press Run (or Ctrl + Enter) to see the console output here.

No output.

break and continue from the previous lesson work in for...of exactly as in other loops.

Objects are not iterable

A plain object doesn't hand out its items in a defined way, so for...of refuses it:

JavaScript
const user = { name: "Ada", role: "admin" };
for (const x of user) {} // TypeError: user is not iterable

To loop over an object with for...of, first turn it into an array with Object.keys(), Object.values() or Object.entries():

JS Looping over an object with for...of

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Object.entries() combined with destructuring is the most common modern way to walk through an object. Working with Objects covers these helpers in detail.

Don't change the array while looping over it

for...of reads the array live, one index at a time. If the body adds or removes items in the same array, the loop sees those changes, which leads to skipped items or loops that never end. For example, removing the current item with splice() shifts the next item into its place, and the loop then jumps right over it. If you need to remove items, build a new array instead (the filter method does exactly that), or loop over a copy: for (const item of [...items]).

for...in: each key of an object

for...in loops over the property names of an object. The variable receives each key as a string:

JS for...in with an object

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice scores[name] with square brackets. The key is stored in a variable, so dot notation (scores.name) would look for a property literally called "name".

Pitfall 1: inherited properties

for...in visits not only an object's own properties, but also enumerable properties it inherits through its prototype. Ordinary object literals inherit nothing enumerable, so you won't usually notice. But objects created from other objects can surprise you:

JavaScript
const defaults = { color: "blue" };
const custom = Object.create(defaults); // custom inherits from defaults
custom.size = "large";

for (const key in custom) {
  console.log(key); // "size", then "color" (inherited!)
}

If you only want the object's own keys, either check with Object.hasOwn(custom, key) inside the loop, or skip for...in and use Object.keys(), which returns only own properties.

Pitfall 2: for...in on arrays

Because arrays are objects, for...in runs on them, which is why this mistake is so common. But it gives you the indexes as strings, not the values, and it also picks up any extra properties someone added to the array:

JS Why not for...in on arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The rule is simple: use for...of for arrays, never for...in.

Key order

Both for...in and Object.keys() follow the same order: keys that look like whole numbers (such as "2" or "10") come first, in ascending numeric order; then the other string keys in the order they were added. So if you use numeric-looking keys, don't rely on insertion order. A Map always keeps insertion order.

Which loop should you use?

You want to… Use
Visit each value of an array, string, Map or Set for...of
Visit each value along with its index for...of with array.entries()
Visit an object's keys and values for...of with Object.entries(obj)
Visit an object's keys, including inherited enumerable ones for...in
Count, step by 2, go backwards, or modify by index Classic for
Transform or filter an array into a new one Array methods like map and filter (coming up)

In modern code, for...in has become fairly rare. Object.entries() with for...of does the same job without the inherited-properties surprise, and it works the same way across all your loops.

Check your understanding

Quick check Β· 5 questions

of 5 answered You scored / 5 Β· perfect!

  1. 1. What does for (const x of ["a", "b"]) give you in x?

    for...of iterates over values. for...in would give the indexes, as strings.
  2. 2. What happens if you use for...of on a plain object like { a: 1 }?

    Plain objects aren't iterable. Use Object.keys(), Object.values() or Object.entries() to get an array first.
  3. 3. Inside for (const i in arr), what is the type of i?

    Property names are strings, so for...in gives array indexes as strings like "0". Adding 1 then concatenates instead of adding.
  4. 4. Which loop visits inherited enumerable properties?

    for...in walks the prototype chain for enumerable properties. Object.keys() and Object.entries() only return the object's own properties.
  5. 5. What is the cleanest modern way to loop over an object's keys and values together?

    Object.entries() returns [key, value] pairs, and destructuring names both parts in the loop header.

Summary

  • for...of gives you the values of any iterable: arrays, strings, Maps, Sets.
  • Use const for the loop variable unless you reassign it inside the body.
  • Get indexes with array.entries(), and walk objects with Object.keys(), Object.values() or Object.entries().
  • Plain objects aren't iterable, so for...of on them throws a TypeError.
  • for...in gives you an object's keys as strings, including inherited enumerable ones.
  • Never use for...in on arrays; use for...of or a classic for.

That completes Control Flow. Next: Functions β€” packaging code into reusable, named pieces.