JavaScript for…of Loop
Learn how to efficiently loop through iterable values in JavaScript using the modern
for…of statement.
The JavaScript for…of loop is used to iterate directly over the values of iterable objects. Unlike traditional loops, it allows you to access each element without managing an index or counter manually.
Introduced in ECMAScript 2015 (ES6), the for…of loop works
seamlessly with built-in iterable data structures such as
arrays, strings, maps, sets, and other iterable objects.
Compared to the traditional for loop or the for…in loop, for…of provides cleaner syntax, improved readability, and fewer errors—making it a preferred choice for modern JavaScript development.
Syntax of JavaScript for…of Loop
for (variable of iterable) {
// code to be executed for each value
}
iterable: Any object that implements the iterable protocol
(such as arrays, strings, sets, or maps).
variable: A temporary variable that stores the current value
during each iteration.
JavaScript for…of Loop with Arrays
Example
const students = ['Ani', 'Affi', 'Rex'];
for (let element of students) {
console.log(element);
}
Try it Yourself »
Explanation:
In this example, the for…of loop iterates through the
students array and logs each student name to the console.
The loop automatically handles iteration without requiring index-based access.
JavaScript for…of with Strings
In JavaScript, the for…of loop can be used to iterate over each character of a string in a clean and readable way.
Example
const message = 'JavaScript';
for (let character of message) {
console.log(character);
}
Try it Yourself »
Explanation:
The for…of loop processes the string one character at a time.
During each iteration, the current character is stored in the
character variable and logged to the console.
JavaScript for…of with Maps
You can iterate over Map objects using the for…of loop. Each iteration returns an array containing both the key and its corresponding value.
Example
const userProfile = new Map();
userProfile.set('username', 'johndoe');
userProfile.set('email', 'john@example.com');
userProfile.set('country', 'USA');
for (const [key, value] of userProfile) {
console.log(`${key}: ${value}`);
}
Try it Yourself »
Explanation:
During each iteration, the for…of loop destructures the
key-value pair returned by the Map. This makes it easy to work with
both values in a clean and readable format.
JavaScript for…of with Sets
The for…of loop can also be used to iterate over Set objects. A Set automatically removes duplicate values and stores only unique entries.
Example
const uniqueNumbers = new Set([10, 20, 30, 20, 40, 10]);
for (const number of uniqueNumbers) {
console.log(number);
}
Try it Yourself »
Explanation:
Even though duplicate values are provided when creating the Set,
only unique values are stored. The for…of loop then
iterates over each unique value in insertion order.
For Loop within a for…of Loop
A nested loop is created when a traditional for loop is placed inside a for…of loop. The outer loop iterates over iterable values, while the inner loop performs repeated operations for each value.
Syntax
for (let value of iterable) {
for (let i = 0; i < limit; i++) {
// code to execute
}
}
Example 1: Adding Numbers Using Nested Loops
Example
const numbers = [5, 10, 15];
for (let num of numbers) {
console.log('Base Number: ' + num);
for (let i = 1; i <= 3; i++) {
console.log(' Result: ' + (num + i));
}
}
Try it Yourself »
Explanation:
The outer for…of loop selects each number from the
numbers array. For each selected number, the inner
for loop adds values from 1 to 3 and prints the result.
This demonstrates how nested loops perform repeated operations
for each array element.
Example 2: Multiplication Tables Using Nested Loops
Example
const tables = [2, 4, 6];
for (let table of tables) {
console.log('Multiplication Table of ' + table);
for (let i = 1; i <= 5; i++) {
console.log(table + ' x ' + i + ' = ' + (table * i));
}
}
Try it Yourself »
Explanation:
The outer for…of loop iterates through the
tables array. For each number, the inner
for loop generates multiplication results from 1 to 5.
This pattern is commonly used for creating tables, reports, and
repeated calculations.
Features of the for…of Loop in JavaScript
1. Simple and Readable Syntax
The JavaScript for…of loop offers a clean and intuitive syntax for iterating over iterable values. Its simplicity minimizes common loop-related errors and makes the code easier to read, understand, and maintain—especially for beginners.
2. Works with Multiple Data Structures
The for…of loop works with all built-in iterable objects, including arrays, strings, sets, maps, and custom iterable objects. This versatility makes it a powerful choice for modern JavaScript applications.
3. Direct Access to Values
Unlike forEach(), which relies on callback functions, the
for…of loop provides direct access to each value within the loop.
This results in clearer logic and more control over how values are processed.
4. Better Control Over Loop Execution
The for…of loop fully supports control flow statements such as
break, continue, and return (inside functions).
This gives developers more flexibility and control compared to
forEach(), which cannot be stopped early.
Difference between for…of and for…in
| for…of | for…in |
|---|---|
| Iterates over the values of iterable objects. | Iterates over the keys (property names) of an object. |
| Ideal for arrays, strings, sets, and maps. | Mainly used for iterating over object properties. |
| Not suitable for plain objects unless they are iterable. | Can be used with arrays, but may lead to unexpected results. |
Frequently Asked Questions (FAQ) – JavaScript for…of Loop
1. What is a for…of loop in JavaScript?
The for…of loop is used to iterate over the values of iterable objects like arrays, strings, maps, and sets. It provides a cleaner syntax compared to traditional loops.
for (let value of [1, 2, 3]) {
console.log(value);
}
2. How does the for…of loop work with arrays?
When used with arrays, the for…of loop iterates directly over each element without needing an index, making the code simpler and more readable.
const fruits = ['Apple', 'Banana', 'Mango'];
for (let fruit of fruits) {
console.log(fruit);
}
3. Can for…of be used with strings?
Yes, strings are iterable in JavaScript. The for…of loop iterates over each character of a string.
const language = 'JavaScript';
for (let char of language) {
console.log(char);
}
4. What is the difference between for…of and for…in?
The for…of loop iterates over values, while
for…in iterates over keys or property names.
Using for…of is recommended for arrays and iterable objects.
const items = ['A', 'B', 'C'];
for (let index in items) {
console.log(index); // keys
}
for (let value of items) {
console.log(value); // values
}
5. Can for…of be used with Map and Set?
Yes, the for…of loop works perfectly with both Map and Set objects.
const user = new Map([
['name', 'John'],
['age', 25]
]);
for (const [key, value] of user) {
console.log(key + ': ' + value);
}