Using a for...of loop in JavaScript is a convenient way to iterate over the elements of an iterable object, such as arrays, strings, and more. Here's an explanation with examples:
Syntax:
for (variable of iterable) {
// Code to be executed for each element in the iterable
}
Example 1: Iterating over an Array
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
In this example, the for...of loop iterates through the
fruits array and prints each element to the console.
Example 2: Iterating over a String
const text = "Hello";
for (const char of text) {
console.log(char);
}
Here, the for...of loop iterates through the characters of the string "Hello" and logs each character.
Example 3: Iterating over a Map
const person = new Map();
person.set("name", "Alice");
person.set("age", 30);
for (const [key, value] of person) {
console.log(key, value);
}
In this example, we iterate through the key-value pairs of a Map using the
for...of loop.
Example 4: Custom Iterable Object
const iterableObject = {
[Symbol.iterator]:
Here, we define a custom iterable object that yields values when iterated with a
for...of loop.
The for...of loop is a versatile way to iterate through various data structures in JavaScript, making your code more concise and readable.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Using a for...of loop in JavaScript is a convenient way to iterate over the elements of an iterable object, such as arrays, strings, and more. Here's an explanation with examples:
Syntax:
Example 1: Iterating over an Array
In this example, the for...of loop iterates through the fruits array and prints each element to the console.
Example 2: Iterating over a String
Here, the for...of loop iterates through the characters of the string "Hello" and logs each character.
Example 3: Iterating over a Map
In this example, we iterate through the key-value pairs of a Map using the for...of loop.
Example 4: Custom Iterable Object
Here, we define a custom iterable object that yields values when iterated with a for...of loop.
The for...of loop is a versatile way to iterate through various data structures in JavaScript, making your code more concise and readable.