References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript for...of statement

Statement JavaScript All modern browsers Updated
Quick answer

The for...of loop iterates over the values of an iterable — an array, string, Map, Set and more. for (const item of array) { ... } gives you each value directly, with no index bookkeeping. Unlike forEach(), you can break out of it and use await inside.

Overview

for...of is the modern, readable way to loop over a collection's values. for (const fruit of fruits) hands you each element in turn — no counter, no array[i] indexing, just the value. It works on anything iterable: arrays, strings (character by character), Map, Set, and the result of Object.entries().

Its key advantage over forEach() is control flow. You can break out of a for...of early and continue to the next value — neither of which forEach() allows. You can also use await inside it to process items sequentially, which forEach() won't do correctly. For looping with the ability to bail out, for...of is the right tool.

Don't confuse it with for...in, which is a different loop: for...of gives you values, while for...in gives you an object's keys (and is meant for objects, not arrays). If you need the index too, pair for...of with array.entries(): for (const [i, value] of array.entries()).

Syntax

for (const value of iterable) {
  // value is each element in turn
}

for (const ch of "hi") { /* "h", "i" */ }
for (const [i, v] of arr.entries()) { /* index + value */ }

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const colors = ['red', 'green', 'blue'];
  const lines = [];

  for (const color of colors) {
    if (color === 'green') continue; // skip green
    lines.push(color);
  }

  document.getElementById('out').textContent = lines.join('\n'); // red / blue
</script>

Best practices

  • Use for...of to loop array (and other iterable) values cleanly, without index juggling.
  • Prefer it over forEach() when you need to break, continue or await.
  • Get the index when needed with for (const [i, value] of arr.entries()).
  • Use for...in for object keys, not for...of — they're different loops.

Frequently asked questions

What is the difference between for...of and for...in?
for...of loops over an iterable's values (arrays, strings, Maps); for...in loops over an object's keys. Use for...of for arrays.
Can I break out of a for...of loop?
Yes. Unlike forEach(), for...of supports break and continue.
How do I get the index in a for...of loop?
Use entries(): for (const [index, value] of array.entries()) { ... }.
Does for...of work with await?
Yes. You can await inside a for...of to process items one after another — something forEach() can't do.