The for...of loop in JavaScript is used to iterate over the values of iterable objects, such as arrays, strings, maps, and sets. It provides a simple way to access each value without manually managing an index or iterator. Unlike the for...in loop, which iterates over enumerable property keys, the for...of loop retrieves values directly from an iterable. In this article, we will learn the syntax, working, examples, advantages, and common mistakes associated with the JavaScript for...of loop.
Table of Contents
What is a for...of Loop in JavaScript?
The for...of loop is a looping statement that processes the values provided by an iterable object, one at a time. An iterable is an object that provides an iterator, allowing its values to be accessed sequentially.
Common iterable objects include:
- Arrays: Used to process collections of elements.
- Strings: Used to access individual Unicode code points.
- Sets: Used to iterate over unique values.
- Maps: Used to iterate over key-value pairs.
- Other iterables: Includes generators and certain built-in collection objects.
The for...of loop is particularly useful when you want to work directly with values instead of property keys or indexes.
Syntax of the for...of Loop
The basic syntax of a JavaScript for...of loop is:
for (variable of iterable) { statements; }
The main components are:
- for: Starts the loop.
- Variable: Receives the current value during each iteration.
- of: Specifies that the loop should iterate over values.
- Iterable: The object that provides values, such as an array or string.
- Loop body: Contains the statements executed for each value.
How Does the for...of Loop Work?
The for...of loop follows these steps:
- JavaScript obtains an iterator from the iterable object.
- The iterator provides the next value.
- The loop variable receives that value.
- The statements inside the loop body execute.
- The process repeats until the iterator has no more values.
When the iteration finishes normally, JavaScript completes the loop and continues with the statements that follow it.
Simple Example of a for...of Loop
The following example demonstrates how to print each element of an array using a for...of loop.
Example:
// JavaScript program to demonstrate a for...of loop
let numbers = [10, 20, 30, 40];
for (let number of numbers) {
console.log(number);
}
Output:
10
20
30
40
In this example, the for...of loop retrieves each value from the numbers array and stores it in the variable number. The value is then printed using console.log().
for...of Loop with Arrays
Arrays are one of the most common uses of the for...of loop. The loop accesses each element directly without requiring an index variable.
Example:
// JavaScript program to iterate through an array
let fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
Output:
Apple
Banana
Mango
Here, the loop processes each fruit in the array. The variable fruit contains the current element during each iteration.
for...of Loop with Strings
Strings are iterable in JavaScript, so a for...of loop can process their Unicode code points one at a time.
Example:
// JavaScript program to iterate through a string
let word = "Hello";
for (let character of word) {
console.log(character);
}
Output:
H
e
l
l
o
In this example, the loop retrieves each character from the string and prints it separately. Unlike indexing by UTF-16 code units, for...of correctly iterates over Unicode code points, including many characters represented by surrogate pairs.
for...of Loop with Sets
A Set is a JavaScript collection that stores unique values. The for...of loop can iterate over those values in insertion order.
Example:
// JavaScript program to iterate through a Set
let numbers = new Set([10, 20, 30, 20]);
for (let number of numbers) {
console.log(number);
}
Output:
10
20
30
In this example, the duplicate value 20 is stored only once in the Set. The loop therefore prints each unique value.
for...of Loop with Maps
A Map stores key-value pairs and allows iteration over those entries. By default, a for...of loop on a Map provides each entry as a two-element array containing the key and value.
Example:
// JavaScript program to iterate through a Map
let student = new Map([
["name", "Rahul"],
["age", 20],
["city", "Pune"]
]);
for (let [key, value] of student) {
console.log(key + ": " + value);
}
Output:
name: Rahul
age: 20
city: Pune
In this example, array destructuring assigns each map entry's key to key and its value to value. The loop then prints both parts of every entry.
for...of Loop with Conditional Statements
A for...of loop can be combined with an if statement to process only values that satisfy a condition.
Example:
// JavaScript program to print even numbers from an array
let numbers = [1, 2, 3, 4, 5, 6];
for (let number of numbers) {
if (number % 2 === 0) {
console.log(number);
}
}
Output:
2
4
6
In this example, the if statement checks whether each number is divisible by 2. Only even numbers are printed.
Using the break Statement in a for...of Loop
The break statement immediately terminates a loop when a specified condition is met.
Example:
// JavaScript program to demonstrate break in a for...of loop
let fruits = ["Apple", "Banana", "Mango", "Orange"];
for (let fruit of fruits) {
if (fruit === "Mango") {
break;
}
console.log(fruit);
}
Output:
Apple
Banana
In this example, the loop stops when the value is "Mango". Since break executes before console.log(), neither "Mango" nor "Orange" is printed.
Using the continue Statement in a for...of Loop
The continue statement skips the remaining statements in the current iteration and moves to the next value.
Example:
// JavaScript program to skip a value in a for...of loop
let numbers = [1, 2, 3, 4, 5];
for (let number of numbers) {
if (number === 3) {
continue;
}
console.log(number);
}
Output:
1
2
4
5
In this example, the loop skips printing 3 and continues with the remaining values in the array.
Difference Between for...in and for...of
Both loops are used to iterate over data in JavaScript, but they work differently.
| Basis | for...in | for...of |
|---|---|---|
| Purpose | Iterates over enumerable property keys | Iterates over values from an iterable |
| Common use | Objects | Arrays, strings, maps, and sets |
| Returned item | Property key | Value |
| Array behavior | Usually returns index keys | Returns array elements |
| Ordinary objects | Can enumerate their properties | Not iterable by default |
| Best use | Accessing object properties | Processing iterable values |
Example of for...in:
// JavaScript program to demonstrate for...in
let fruits = ["Apple", "Banana", "Mango"];
for (let index in fruits) {
console.log(index);
}
Output:
0
1
2
Example of for...of:
// JavaScript program to demonstrate for...of
let fruits = ["Apple", "Banana", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
Output:
Apple
Banana
Mango
The for...in loop returns the array's enumerable index keys, while the for...of loop returns its values. Use for...of when you need to process array elements directly.
Advantages of the for...of Loop
The JavaScript for...of loop offers several advantages:
-
Simple syntax: It provides a clear way to iterate over values without manually managing indexes.
-
Readable code: It makes iteration easier to understand, especially when working with arrays.
-
Supports multiple iterables: It works with arrays, strings, maps, sets, and other iterable objects.
-
Supports loop control: It works with statements such as break and continue.
-
Reduces indexing errors: It avoids manually calculating array indexes when only the values are needed.
Common Beginner Mistakes
1. Using for...of with an ordinary object: Plain objects are not iterable by default, so for...of on an ordinary object throws a TypeError. Use Object.keys(), Object.values(), or Object.entries() to iterate over its properties.
2. Confusing for...of with for...in: The for...of loop returns values, while for...in returns property keys. Choose the loop based on what you need to access.
3. Expecting indexes from for...of: A for...of loop over an array returns elements, not indexes. Use array.entries() if both the index and value are required.
4. Modifying an array during iteration: Adding or removing elements while iterating can lead to unexpected results. Avoid changing the collection during iteration unless the behavior is intentional.
5. Assuming for...of works with every object: The loop requires an iterable object. If a value is not iterable, JavaScript throws a TypeError.
Conclusion
The for...of loop in JavaScript is a convenient way to iterate over values provided by iterable objects, including arrays, strings, maps, and sets. It improves readability by removing the need to manage indexes manually and supports useful control statements such as break and continue. Understanding the difference between for...of and for...in helps developers choose the right loop for each task.
FAQs
-
What is a for...of loop in JavaScript?
A for...of loop iterates over the values provided by an iterable object, such as an array, string, map, or set.
-
Can the for...of loop be used with arrays?
Yes. It retrieves each array element directly, making it useful for processing array values.
-
What is the difference between for...in and for...of?
The for...in loop iterates over enumerable property keys, while the for...of loop iterates over values from an iterable.
-
Can for...of be used with ordinary JavaScript objects?
Not directly. Ordinary objects are not iterable by default, but you can use Object.keys(), Object.values(), or Object.entries() to iterate over their properties.
-
How can you get both the index and value using for...of?
You can use for (let [index, value] of array.entries()) to access both the index and the corresponding value during each iteration.
0 Comments