In JavaScript, the `for...of` loop is used to iterate over the elements of an iterable object, such as arrays, strings, maps, sets, and more. It provides a concise and readable way to loop through the elements without needing to deal with index values or keys. Here's the syntax of the `for...of` loop:
for (variable of iterable) {
// Code block to be executed
}
const fruits = ['apple', 'banana', 'orange'];
for (let fruit of fruits) {
console.log(fruit);
}
apple
banana
orange
const message = 'Hello';
for (let char of message) {
console.log(char);
}
Output:
H
e
l
l
o
const map = new Map([
['name', 'John'],
['age', 30]
]);
for (let [key, value] of map) {
console.log(key + ': ' + value);
}
Output:
name: John
age: 30
The for...of loop simplifies the process of iterating over elements in iterable objects, making your code cleaner and more expressive. It's a powerful feature introduced in ECMAScript 6 (ES6) and is widely used in modern JavaScript development.