JavaScript tutorials > JavaScript Basics > Control Structures > What is a for...of loop used for?

What is a for...of loop used for?

The for...of loop in JavaScript is a powerful construct for iterating over iterable objects like arrays, strings, maps, sets, and more. It provides a clean and concise way to access the values within these collections without the need for manual indexing. This tutorial explores the purpose, syntax, use cases, and best practices of the for...of loop.

Introduction to the for...of Loop

The for...of loop is designed to iterate over the values of iterable objects, rather than the indices or keys. This distinguishes it from the for loop or for...in loop. An iterable object is any object that defines a method that returns an iterator. Common examples of iterables include arrays, strings, Maps, Sets, and the arguments object.

Syntax of the for...of Loop

The syntax is straightforward. element represents a variable that will hold the value of each element in the iterable during each iteration. iterable is the object you want to iterate over, such as an array or string. The code block within the curly braces will be executed once for each element in the iterable.

for (const element of iterable) {
  // Code to be executed for each element
}

Iterating Over an Array

This example demonstrates iterating over an array of strings. The fruit variable will take on the values 'apple', 'banana', and 'cherry' respectively, during each iteration of the loop. The output will be: apple banana cherry

const myArray = ['apple', 'banana', 'cherry'];

for (const fruit of myArray) {
  console.log(fruit);
}

Iterating Over a String

Strings are also iterable in JavaScript. In this example, the character variable will hold each character in the string 'Hello' during each iteration. The output will be: H e l l o

const myString = 'Hello';

for (const character of myString) {
  console.log(character);
}

Iterating Over a Set

Sets are collections of unique values. The for...of loop iterates over the values in the set in the order they were inserted. The output will be: apple banana cherry

const mySet = new Set(['apple', 'banana', 'cherry']);

for (const fruit of mySet) {
  console.log(fruit);
}

Iterating Over a Map

Maps are collections of key-value pairs. When iterating over a Map with for...of, each element is an array containing the key and value. Destructuring is commonly used to easily access the key and value separately. The output will be: Key: a, Value: 1 Key: b, Value: 2 Key: c, Value: 3

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

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

Concepts Behind the Snippet

The for...of loop leverages the concept of iterators. An iterator is an object that defines a next() method, which returns an object with two properties: value (the next value in the sequence) and done (a boolean indicating whether the iteration is complete). The for...of loop automatically handles calling the next() method and checking the done property, making iteration more convenient.

Real-Life Use Case: Processing User Input

Imagine you need to validate user input character by character. The for...of loop provides an easy way to iterate through each character of the input string and perform validation checks. This example iterates through characters entered into an input field and checks if they are alphanumeric.

const userInput = document.getElementById('myInput').value;

for (const char of userInput) {
  // Validate each character of the user input
  if (!/^[a-zA-Z0-9]$/.test(char)) {
    console.log(`Invalid character: ${char}`);
  }
}

Best Practices

  • Use const or let: Always declare the loop variable (e.g., fruit, character) with const if the value is not reassigned within the loop, and let if you need to modify it.
  • Avoid modifying the iterable during iteration: Adding or removing elements from the iterable while iterating can lead to unexpected behavior.
  • Use destructuring for Maps: When iterating over Maps, use destructuring (const [key, value] of myMap) for cleaner code.

Interview Tip

Be prepared to explain the difference between the for...of and for...in loops. The for...of loop iterates over the values of iterable objects, while the for...in loop iterates over the keys (or property names) of an object. Also, mention that for...in should not be used with Arrays because the order of iteration is not guaranteed and it includes inherited properties.

When to use them

Use the for...of loop when you need to iterate over the values of an iterable object and you don't need the index or key. It's particularly useful for arrays, strings, Sets, and Maps. Avoid using it for plain JavaScript objects (use for...in or Object.keys() instead).

Memory Footprint

The memory footprint of a for...of loop is generally efficient, as it iterates directly over the values without creating unnecessary copies of the iterable. However, if the iterable itself is large, that will, of course, require more memory. The for...of construct itself introduces minimal overhead.

Alternatives: for, forEach, for...in

  • for loop: Provides more control over the iteration process but requires manual indexing.
  • forEach() method: A higher-order function that iterates over an array. It's more concise than a for loop but cannot be easily broken out of (you can't use break or continue).
  • for...in loop: Iterates over the keys of an object. Not suitable for arrays due to iteration order and inherited properties.

Pros

  • Concise and readable: Simplifies iteration code.
  • Iterates over values directly: Eliminates the need for manual indexing.
  • Works with various iterable objects: Supports arrays, strings, Sets, Maps, and more.

Cons

  • No access to index: If you need the index of the element, you'll need to use a different approach (e.g., a traditional for loop or forEach with index).
  • Not suitable for plain objects: Doesn't directly iterate over the properties of plain JavaScript objects.

FAQ

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

    The for...of loop iterates over the values of an iterable object (like an array), while the for...in loop iterates over the keys (property names) of an object. Use for...of for arrays, strings, Sets, and Maps, and for...in for iterating over the properties of plain JavaScript objects. Be cautious with for...in on arrays as the order isn't guaranteed and it iterates over inherited properties.
  • Can I use break and continue in a for...of loop?

    Yes, you can use break to exit the loop prematurely and continue to skip to the next iteration.
  • Does for...of work with plain JavaScript objects?

    No, for...of does not directly work with plain JavaScript objects. You can use Object.keys(), Object.values(), or Object.entries() to get an array of keys, values, or key-value pairs, respectively, and then iterate over that array using for...of.