JavaScript Loop For Of

JavaScript provides several looping structures to handle iteration tasks efficiently. The for…of loop is a modern and intuitive way to iterate over iterable objects such as arrays, strings, maps and sets. Unlike for and for…in loops, the for…of loop focuses on values rather than indices or keys, making it ideal for clean and readable code.

What is the For…Of Loop?

The for…of loop is a control structure introduced in ES6 (ECMAScript 2015). It allows you to iterate over the values of an iterable object, providing a straightforward way to access each element.

Syntax

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

Parameters:

  • variable: A variable that stores the current value from the iterable during each iteration.
  • iterable: The object you want to iterate over (e.g., an array, string, map or set).

Key Difference: For…In vs. For…Of

FeatureFor…InFor…Of
FocusIterates over keys/indexes.Iterates over values.
Use CaseObjects and sparse arrays.Arrays, strings, maps, sets, etc.
OutputProperty names (keys).Property values.

Example 1: Iterating Over an Array

const languages = ["JavaScript", "Python", "Ruby"];

for (let language of languages) {
console.log(language);
}
// Output:
// JavaScript
// Python
// Ruby

Explanation:

  • The loop retrieves each value (JavaScript, Python, Ruby) from the array one by one and assigns it to the language variable.

Example 2: Iterating Over a String

Strings are iterable objects in JavaScript. You can use the for…of loop to access each character.

const word = "Hello";

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

Explanation:

  • The loop processes each character in the string (H, e, l, l, o,) sequentially.

Example 3: Iterating Over a Map

The for…of loop is especially useful with Map objects, allowing you to iterate over key-value pairs.

const user = new Map([
["name", "Alice"],
["age", 25],
["profession", "Developer"]
]);

for (let [key, value] of user) {
console.log(`${key}: ${value}`);
}
// Output:
// name: Alice
// age: 25
// profession: Developer

Explanation:

  • The Map object provides entries (key-value pairs) for iteration.
  • Using destructuring ([key, value]), the loop assigns the pair to separate variables for better readability.

Example 4: Iterating Over a Set

The for…of loop also works seamlessly with Set objects, iterating over unique values.

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

for (let num of numbers) {
console.log(num);
}
// Output:
// 1
// 2
// 3
// 4

Explanation:

  • The Set automatically removes duplicates and the loop retrieves each unique value (1, 2, 3, 4).

Example 5: Using For…Of with Generators

Generators produce iterable sequences, which can be accessed using the for…of loop.

function* generateNumbers() {
yield 1;
yield 2;
yield 3;
}

for (let num of generateNumbers()) {
console.log(num);
}
// Output:
// 1
// 2
// 3

Explanation:

  • The generator function generateNumbers yields values one at a time.
  • The for…of loop retrieves and processes each yielded value.

Key Features of the For…Of Loop

  1. Focus on Values: The loop directly accesses the values of iterable objects, simplifying code.
  2. Wide Compatibility: Works with all iterable objects, including arrays, strings, maps, sets and generators.
  3. Readable Code: Provides a clean and concise way to process data without dealing with indices or keys.

Common Use Cases of For…Of

  1. Processing Arrays:
    Ideal for iterating over array elements, particularly in non-index-specific operations.
  2. Working with Strings:
    Access each character in a string for manipulation or analysis.
  3. Handling Maps and Sets:
    Simplifies iteration over maps (key-value pairs) and sets (unique values).
  4. Iterating Custom Iterables:
    Perfect for processing objects with a custom iterable protocol, including generators.

Best Practices

  1. Use for Iterables Only: Ensure the object is iterable (e.g., array, string, map) to avoid errors.
  2. Avoid with Objects: The for…of loop does not work with plain objects. Use for…in or Object.keys() for objects.
  3. Combine with Destructuring: Use destructuring with maps or arrays for more readable code.

Example 6: Comparing For…Of with ForEach

const fruits = ["Apple", "Banana", "Cherry"];

// For...Of
for (let fruit of fruits) {
console.log(fruit); // Outputs: Apple, Banana, Cherry
}

// ForEach
fruits.forEach((fruit) => {
console.log(fruit); // Outputs: Apple, Banana, Cherry
});

Differences:

  • The for…of loop provides better flexibility with break and continue statements, which are not supported in forEach.

Advantages of For…Of

  1. Simplified Iteration: Focuses on values, eliminating the need to manually retrieve elements.
  2. Flexibility: Works with multiple iterable types, making it versatile.
  3. Better Flow Control: Supports break and continue for more control over the loop.

Leave a Comment