Javascript
JS Loops
Javscript For...of Loop

1. Iterating Over an Array using for...of

const a = [1, 2, 3, 4, 5];
 
for (const item of a) {
    console.log(item);
}

Output:

1
2
3
4
5

Preferred Loops for Iterables

  • Use for...of if we need to use continue or break in the loop.
  • Use forEach() if we need to execute something for all elements without any condition.
  • Use for...in for iterating over object properties.

2. Iterating Over a String using for...of

const str = "Hello";
 
for (const char of str) {
    console.log(char);
}

Output:

H
e
l
l
o

3. Iterating Over a Map using for...of

const m = new Map([
    ["name", "Akash"],
    ["age", 25],
    ["city", "Noida"]
]);
 
for (let [key, value] of m) {
    console.log(`${key}: ${value}`);
}

Output:

name: Akash
age: 25
city: Noida

4. Iterating Over a Set using for...of

let s = new Set([1, 2, 3, 4, 5]);
 
for (let val of s) {
    console.log(val);
}

Output:

1
2
3
4
5

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.

let person = {
    name: "Akash",
    age: 25,
    city: "Noida"
};
 
for (let key of Object.keys(person)) {
    console.log(`${key}: ${person[key]}`);
}

Output:

name: Akash
age: 25
city: Noida

JavaScript for...of Loop

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 a 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().