The for...of
loop in JavaScript is used to iterate over iterable objects such as arrays, strings, maps, and sets. It provides a simple and concise way to access each element of the collection without the need for manual indexing.
Here’s the basic syntax of the for...of
loop:
for (variable of iterable) {
// code to be executed for each element
}
This loop is particularly useful when you want to perform an operation on every item in the collection without worrying about indices or length.
JavaScript for of loop example
Simple example code.
Iterating over an array using for-of
const array = [1, 2, 3, 4, 5];
for (const element of array) {
console.log(element);
}
// Output: 1 2 3 4 5
for…of Iterating over a string
const str = 'Hello';
for (const char of str) {
console.log(char);
}
// Output: H e l l o
Iterating over a map
const map = new Map();
map.set('name', 'John');
map.set('age', 30);
map.set('country', 'USA');
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
Output:
Iterating over a set
const set = new Set([1, 2, 3, 4, 5]);
for (const element of set) {
console.log(element);
}
// Output: 1 2 3 4 5
The for...of
loop only works with iterable objects. If you need to iterate over plain objects or arrays-like objects, you would typically use the for...in
loop instead.
Comment if you have any doubts or suggestions on this Js Loop topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version