Skip to main content

Archive

Show more

JavaScript for...of Loop

JavaScript for...of Loop

The for...of loop in JavaScript is used to iterate over iterable objects such as arrays, strings, maps, sets, and more. Unlike the for...in loop, which iterates over the enumerable properties of an object, the for...of loop iterates directly over the values of an iterable object, making it ideal for handling data in collections.


Basic Syntax of the for...of Loop

The basic syntax of the for...of loop is:

for (variable of iterable) {
  // Code to execute for each value
}

Here:

  • variable is the name of the variable that will store the current value from the iterable object during each iteration.
  • iterable is an object that is iterable, such as an array, string, or any other collection.

Example: Iterating Over an Array

The for...of loop is most commonly used with arrays. Here’s an example of how to iterate over an array:

const colors = ['red', 'green', 'blue'];

for (const color of colors) {
  console.log(color);
}
// Output:
// red
// green
// blue
  • The for...of loop iterates over each element in the colors array.
  • During each iteration, the current element is stored in the color variable and logged to the console.

Example: Iterating Over a String

The for...of loop can also be used to iterate over each character in a string:

const message = 'Hello';

for (const char of message) {
  console.log(char);
}
// Output:
// H
// e
// l
// l
// o

In this example, the loop iterates over each character in the string message, logging each character individually.


Example: Iterating Over a Map

The for...of loop can be used with Map objects to iterate over key-value pairs:

const userRoles = new Map();
userRoles.set('Alice', 'Admin');
userRoles.set('Bob', 'Editor');

for (const [user, role] of userRoles) {
  console.log(`${user}: ${role}`);
}
// Output:
// Alice: Admin
// Bob: Editor
  • The for...of loop iterates over each key-value pair in the userRoles map.
  • The current key-value pair is destructured into the user and role variables during each iteration.

Example: Iterating Over a Set

The for...of loop is also compatible with Set objects:

const uniqueNumbers = new Set([1, 2, 3, 4, 5]);

for (const number of uniqueNumbers) {
  console.log(number);
}
// Output:
// 1
// 2
// 3
// 4
// 5

In this example, the for...of loop iterates over each unique number in the uniqueNumbers set.


Using the break and continue Statements

The break and continue statements can be used within a for...of loop to control the flow of the loop:

const numbers = [1, 2, 3, 4, 5];

for (const num of numbers) {
  if (num === 3) {
    continue; // Skip number 3
  }
  if (num > 4) {
    break; // Stop the loop when number is greater than 4
  }
  console.log(num);
}
// Output:
// 1
// 2
// 4
  • The loop skips the number 3 using the continue statement.
  • The loop stops once it encounters a number greater than 4 due to the break statement.

Performance Considerations

The for...of loop provides a simple and readable way to iterate over iterable objects. However, it may not be as performant as a standard for loop in situations where the iteration count is known beforehand or when working with large datasets. It's important to choose the right loop based on the specific use case.


Conclusion

The for...of loop is a versatile and powerful tool for iterating over iterable objects in JavaScript, such as arrays, strings, maps, and sets. It simplifies the process of accessing values directly and is especially useful when working with collections. Understanding how to use the for...of loop effectively will help you write cleaner and more concise JavaScript code.

Comments