for…of
The for...of
loop in JavaScript is used to iterate over iterable objects, such as arrays, strings, maps, sets, and more. It provides a cleaner syntax compared to traditional for
loops when working with arrays and other iterable objects. Here's how it works with some code examples:
- Iterating over an array using
for...of
:
const colors = ['red', 'green', 'blue'];
for (const color of colors) {
console.log(color);
}
// Output:
// red
// green
// blue
In this example, the for...of
loop iterates over each element of the colors
array, assigning each element in turn to the variable color
, and then logs each color to the console.
- Iterating over a string using
for...of
:
const str = 'hello';
for (const char of str) {
console.log(char);
}
// Output:
// h
// e
// l
// l
// o
Here, the for...of
loop iterates over each character of the string str
, assigning each character in turn to the variable char
, and then logs each character to the console.
- Iterating over a map using
for...of
:
const myMap = new Map([
['a', 1],
['b', 2],
['c', 3]
]);
for (const [key, value] of myMap) {
console.log(key, value);
}
// Output:
// a 1
// b 2
// c 3
In this example, the for...of
loop iterates over each key-value pair of the map myMap
, destructuring the key-value pair into variables key
and value
, and then logs each key-value pair to the console.
- Iterating over a set using
for...of
:
const mySet = new Set([1, 2, 3]);
for (const value of mySet) {
console.log(value);
}
// Output:
// 1
// 2
// 3
Here, the for...of
loop iterates over each element of the set mySet
, assigning each element in turn to the variable value
, and then logs each value to the console.
In summary, the for...of
loop provides a concise and readable way to iterate over iterable objects in JavaScript, making it easier to work with arrays, strings, maps, sets, and other iterable objects.
Leave a Comment