JavaScript For-Of loops are essential for iterating over iterable objects like arrays, strings, and more. They provide a concise and convenient way to traverse data structures in your code. In this comprehensive guide, we will explore JavaScript For-Of loops in depth, providing detailed explanations and practical real-world examples to help you become proficient in using them effectively.
1. Understanding the Role of For-Of Loops
JavaScript For-Of loops simplify iterable iteration, making them valuable for working with data collections.
2. The Basic For-Of Loop
Learn how to use the basic for-of
loop to iterate over the elements of an iterable.
Example:
let colors = ["red", "green", "blue"];
for (let color of colors) {
console.log("Color: " + color);
}
3. Iterating Over Strings
Discover how For-Of loops can be used to loop through the characters of a string.
Example:
let message = "Hello, World!";
for (let char of message) {
console.log("Character: " + char);
}
4. Iterating Over Maps
Learn how to use For-Of loops to iterate over the key-value pairs of a Map.
Example:
let employeeDetails = new Map();
employeeDetails.set("name", "John");
employeeDetails.set("age", 30);
for (let [key, value] of employeeDetails) {
console.log(key + ": " + value);
}
5. Iterating Over Sets
Explore how For-Of loops can be used to iterate over the elements of a Set.
Example:
let uniqueNumbers = new Set([1, 2, 3, 4, 5]);
for (let number of uniqueNumbers) {
console.log("Number: " + number);
}
6. Iterating Over Custom Iterables
Learn how to create custom iterable objects and use For-Of loops to traverse them.
Example:
let customIterable = {
[Symbol.iterator]() {
let values = [10, 20, 30];
let index = 0;
return {
next() {
if (index < values.length) {
return { value: values[index++], done: false };
} else {
return { done: true };
}
}
};
}
};
for (let value of customIterable) {
console.log("Value: " + value);
}