A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-for-of-loop/ below:

JavaScript for...of Loop - GeeksforGeeks

JavaScript for...of Loop

Last Updated : 21 Nov, 2024

The JavaScript for...of loop is a modern, iteration statement introduced in ECMAScript 2015 (ES6).

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 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}`);
}

Output
name: 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]}`);
}

Output
name: Akash
age: 25
city: Noida

Recommended Links:



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4