The JavaScript for…of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6).
- Works for iterable objects such as arrays, strings, maps, sets, and more.
- It is better choice for traversing items of iterables compared to traditional for and for in loops, especially when we have break or continue statements. If we just want to perform an operation on all items, we prefer forEach()
1. Iterating Over an Array using for…of
JavaScript
const a = [ 1, 2, 3, 4, 5 ];
for (const item of a) {
console.log(item);
}
For iterables , the below loops are preferred.
- For of Loop if we need to put continue or break in the loop
- forEach() if we need execute something for all elements without any condition
For Objects, for in loop is better suited.
2. Iterating Over a String using for…of
JavaScript
const str = "Hello";
for (const char of str) {
console.log(char);
}
3. Iterating Over a Map using for…of
JavaScript
const m = new Map([
["name", "Akash"],
["age", 25],
["city", "Noida"]
]);
for (let [key, value] of m) {
console.log(`${key}: ${value}`);
}
Outputname: Akash
age: 25
city: Noida
4. Iterating Over a Set using for…of
JavaScript
let s = new Set([1, 2, 3, 4, 5]);
for (let val of s) {
console.log(val);
}
5. Iterating Over an Objectâs Properties using for…of
While the for…of loop is not directly used to iterate over object properties, you can use it in combination with Object.keys(), Object.values(), or Object.entries() to achieve this.
JavaScript
let person = {
name: "Akash",
age: 25,
city: "Noida"
};
for (let key of Object.keys(person)) {
console.log(`${key}: ${person[key]}`);
}
Outputname: Akash
age: 25
city: Noida
Recommended Links:
JavaScript for…of Loop – FAQs
What is a for-of loop in JavaScript?
A for-of loop is a control structure that allows you to iterate over the values of an iterable object, such as arrays, strings, maps, sets, and more. This loop is designed to traverse the values directly rather than the keys or indices.
What is the basic syntax of a for-of loop?
The basic syntax of a for-of loop includes the for keyword, followed by a variable to hold each value, the of keyword, and the iterable object to iterate over. The code block to be executed for each value is placed inside curly braces.
How does the for-of loop work?
The for-of loop iterates over the values of an iterable object. For each value, the loop assigns the value to the specified variable and executes the code block.
What is the difference between for-of and for-in loops?
for-of loop: Iterates over the values of an iterable object (such as arrays, strings, maps, etc.).
for-in loop: Iterates over the enumerable properties (keys) of an object.
Can a for-of loop be used with objects?
A for-of loop cannot be used directly with objects because objects are not inherently iterable. However, you can use a for-of loop in conjunction with Object.keys(), Object.values(), or Object.entries() to iterate over an object’s keys, values, or key-value pairs.