JavaScript > ES6 and Beyond > Iterators and Generators > for...of loop

Iterating with for...of: A Modern Approach

The for...of loop in JavaScript (ES6 and beyond) offers a concise and readable way to iterate over iterable objects like arrays, strings, Maps, Sets, and more. This snippet explores its usage and advantages compared to traditional loops.

Basic Usage of for...of

The for...of loop iterates directly over the values of an iterable. Unlike for...in, which iterates over the keys of an object, for...of provides the values themselves. The examples demonstrate iterating over arrays, strings, Maps, and Sets. Note how for Maps, destructuring is used to access both the key and the value within the loop.

// Iterating over an array
const myArray = [1, 2, 3, 4, 5];

console.log("Iterating over myArray:");
for (const element of myArray) {
  console.log(element);
}

// Iterating over a string
const myString = "Hello";

console.log("Iterating over myString:");
for (const character of myString) {
  console.log(character);
}

// Iterating over a Map
const myMap = new Map();
myMap.set('a', 1);
myMap.set('b', 2);
myMap.set('c', 3);

console.log("Iterating over myMap:");
for (const [key, value] of myMap) {
  console.log(`Key: ${key}, Value: ${value}`);
}

// Iterating over a Set
const mySet = new Set([1, 2, 2, 3, 3, 3]); // Sets only store unique values

console.log("Iterating over mySet:");
for (const value of mySet) {
  console.log(value);
}

Concepts Behind the Snippet

The for...of loop relies on the concept of iterables and iterators. An iterable is an object that defines a method whose key is Symbol.iterator. This method returns an iterator object. The iterator object defines a next() method that returns an object with two properties: value (the next value in the sequence) and done (a boolean indicating whether the sequence is finished). The for...of loop automatically handles calling the next() method and extracting the value until done is true.

Real-Life Use Case

Imagine processing a list of user names fetched from an API. Instead of manually managing indices with a traditional for loop, you can use for...of to iterate directly over the user name array. Similarly, you might use it to process the characters of a user-entered search query to validate inputs or apply formatting.

Best Practices

  • Use const to declare the loop variable unless you need to modify the value within the loop.
  • Avoid modifying the iterable object within the loop, as this can lead to unexpected behavior.
  • Use break to exit the loop early if necessary.
  • Use continue to skip to the next iteration if a specific condition is met.

Interview Tip

Be prepared to explain the difference between for...of and for...in loops. Emphasize that for...of iterates over values of iterables, while for...in iterates over keys of objects. Also, mention the usage of iterators and the Symbol.iterator method.

When to Use Them

Use for...of when you need to iterate over the values of an iterable object (arrays, strings, Maps, Sets, etc.). It's generally preferred over traditional for loops for its readability and conciseness, especially when you don't need the index.

Memory Footprint

for...of has a generally comparable memory footprint to traditional for loops. The memory usage mainly depends on the size of the iterable object itself. The for...of loop itself doesn't introduce significant overhead.

Alternatives

  • Traditional for loop: Useful when you need the index or more fine-grained control over the iteration.
  • forEach() method: Another way to iterate over arrays, but it cannot be easily stopped using break or continue.
  • for...in loop: Use with caution, as it iterates over keys of objects, which may not be what you intend.

Pros

  • Readability: More concise and easier to understand than traditional for loops.
  • Direct Value Access: Directly iterates over the values of the iterable.
  • Works with Various Iterables: Supports arrays, strings, Maps, Sets, and custom iterables.

Cons

  • No Index Access: Does not provide direct access to the index of the element. If you need the index, you might need to use a traditional for loop or track the index manually.
  • Not Suitable for All Objects: Only works with iterable objects. It will not work with plain JavaScript objects unless they implement the iterable protocol.

FAQ

  • What is the difference between for...of and for...in?

    for...of iterates over the values of an iterable object (e.g., array elements, string characters), while for...in iterates over the keys (property names) of an object. for...in is generally not recommended for iterating over arrays because the order of iteration is not guaranteed and it can also iterate over inherited properties.
  • Can I use for...of with plain JavaScript objects?

    No, for...of only works with iterable objects. Plain JavaScript objects are not iterable by default. To iterate over the properties of a plain object, you can use for...in or Object.keys(), Object.values(), or Object.entries() in conjunction with a for...of loop.
  • How does for...of handle errors?

    for...of handles errors in the same way as other JavaScript control flow structures. If an error is thrown within the loop, it will propagate up the call stack unless it is caught by a try...catch block.