You are currently viewing JavaScript Cheat Sheet 10.38: JavaScript For Of

JavaScript Cheat Sheet 10.38: JavaScript For Of

Mastering JavaScript’s For Of Loop


Welcome to the exciting world of JavaScript programming! In this tutorial, we’ll delve into one of the fundamental concepts in JavaScript – the for...of loop. This loop is a powerful tool for iterating over iterable objects, making your code more concise and readable. By the end of this tutorial, you’ll have a solid understanding of how to use the for...of loop and its applications in real-world scenarios.


Section 1: Understanding Iterables

Overview:
Before diving into the for...of loop, it’s crucial to grasp the concept of iterable objects. Iterable objects are those that can be iterated over, meaning you can access their elements one at a time. Examples of iterable objects in JavaScript include arrays, strings, maps, sets, etc.

Example Code:

// Array as an iterable
const myArray = [1, 2, 3, 4, 5];

// String as an iterable
const myString = "Hello";

// Map as an iterable
const myMap = new Map([['a', 1], ['b', 2]]);

Section 2: Introduction to the For Of Loop

Overview:
The for...of loop is a concise and clean way to iterate over iterable objects. It simplifies the process of accessing each element without dealing with the complexities of index management.

Example Code:

// Using for...of loop with an array
const myArray = [1, 2, 3, 4, 5];

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

// Output: 1, 2, 3, 4, 5

Explanation:

  • We declare a variable element to represent each element in the array.
  • The loop iterates over the array, and in each iteration, the value of element is the current array element.
  • The console.log(element) statement prints each element to the console.

Section 3: Iterating Over Strings

Overview:
The for...of loop is not limited to arrays; it’s equally effective for iterating over the characters of a string.

Example Code:

// Using for...of loop with a string
const myString = "Hello";

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

// Output: H, e, l, l, o

Explanation:

  • Here, the loop iterates over each character in the string, and char represents the current character in each iteration.
  • The console.log(char) statement prints each character to the console.

Section 4: Working with Maps

Overview:
The for...of loop can also iterate over the entries of a Map, providing a convenient way to work with key-value pairs.

Example Code:

// Using for...of loop with a Map
const myMap = new Map([['a', 1], ['b', 2]]);

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

// Output: Key: a, Value: 1
//         Key: b, Value: 2

Explanation:

  • The loop iterates over each entry in the Map, where [key, value] represents the key-value pair.
  • The console.log statement prints each key and value to the console.

Section 5: Using For Of with Custom Iterables

Overview:
You can also use the for...of loop with custom iterable objects by defining the Symbol.iterator method.

Example Code:

// Custom iterable object
const myIterable = {
    values: [10, 20, 30],
    [Symbol.iterator]: function () {
        let index = 0;
        return {
            next: () => ({
                value: this.values[index++],
                done: index > this.values.length
            })
        };
    }
};

// Using for...of loop with a custom iterable
for (const value of myIterable) {
    console.log(value);
}

// Output: 10, 20, 30

Explanation:

  • The custom iterable object myIterable has an array of values and a Symbol.iterator method.
  • The for...of loop iterates over the custom iterable, accessing each value through the value variable.
  • The console.log(value) statement prints each value to the console.

Conclusion:
Congratulations! You’ve now mastered the for...of loop in JavaScript. This powerful loop enhances the readability and simplicity of your code when working with iterable objects. Practice and experiment with different iterable types to solidify your understanding, and you’ll be well on your way to becoming a proficient JavaScript programmer.

Remember, the for...of loop is a valuable tool in your programming arsenal, making your code more expressive and efficient. Happy coding!

Leave a Reply