JavaScript for...of Loop

The for...of loop, introduced in ES6 (ECMAScript 2015), is a modern and highly readable way to iterate over data. Unlike older looping methods, it focuses directly on the values of an iterable object rather than their indices or keys. This makes your code more expressive and significantly reduces the boilerplate required to process collections.

Best Practice: Use for...of whenever you need to process every element in an array or collection and don't specifically need the index number. It makes your code much cleaner and easier for other developers to scan.

Why it is Used:

  • Readability: It provides a clean, declarative syntax that clearly communicates your intent: "for every item of this collection, do this."
  • Value-Focused: It extracts the actual value directly, so you don't have to write myArray[i] every time you want to access an element.
  • Broad Compatibility: It works out-of-the-box with Arrays, Strings, NodeLists (from the DOM), Maps, Sets, and even custom generators.
  • Control Flow: Unlike the .forEach() method, for...of allows you to use break, continue, and return statements, giving you full control over the loop's execution.
Developer Tip: Use for...of when you need to use await inside a loop. It handles asynchronous operations sequentially, whereas forEach can lead to unexpected behavior with async/await.

Syntax:

for (const value of iterable) {
  // Logic to process the value
}
  • Variable: On each iteration, the current value is assigned to this variable. You can use let or const.
  • Iterable: Any object that has the "iterable protocol" (like an Array, Map, or String).
Best Practice: Use const in the loop head (e.g., for (const item of items)) if you aren't reassigning the variable within the loop block. This ensures the value remains immutable during that specific iteration.

Examples:

Iterating Over an Array:

This is the most common use case. It replaces the traditional for (let i = 0; i < arr.length; i++) approach.

const projects = ['Website Redesign', 'API Integration', 'Mobile App'];

for (const project of projects) {
  console.log(`Current Project: ${project}`);
}
Common Mistake: Trying to use for...of on a standard Object. Objects are not iterable by default. If you try to loop over { name: 'John' }, you will get a TypeError. Use Object.keys() or Object.entries() instead.

Extracting Unique Characters from a String:

Strings are iterable in JavaScript, meaning for...of treats the string as a sequence of characters.

const sentence = 'code more';
let uniqueChars = new Set();

for (const char of sentence) {
  if (char !== ' ') {
    uniqueChars.add(char);
  }
}

console.log('Unique Characters found:', [...uniqueChars].join(', '));

Iterating Over a Map:

When looping over a Map, each entry is returned as an array [key, value]. You can use array destructuring to make this very readable.

const userRoles = new Map([
  ['Alice', 'Admin'],
  ['Bob', 'Editor'],
  ['Charlie', 'Viewer']
]);

// Destructuring [key, value] directly in the loop
for (const [user, role] of userRoles) {
  console.log(`${user} has the role of: ${role}`);
}

Filtering Even Numbers in an Array:

While .filter() is a great functional approach, for...of is excellent when you need to perform more complex logic or side effects while filtering.

const dataPoints = [12, 5, 8, 130, 44];
const evenResults = [];

for (const point of dataPoints) {
  if (point % 2 === 0) {
    console.log('Processing even point:', point);
    evenResults.push(point);
  }
}
Watch Out: Do not confuse for...of with for...in. for...in iterates over the property names (keys) of an object, whereas for...of iterates over the values of an iterable. Using for...in on an array will give you indices (0, 1, 2) as strings!

 

Summary

The for...of loop is the gold standard for iterating over collections in modern JavaScript. It removes the mental overhead of managing counters and array bounds, allowing you to focus on the actual data logic. Whether you are handling a list of DOM elements, processing a Set of unique IDs, or destructuring keys and values from a Map, for...of provides the most readable and flexible solution available.