How to use for…of loop in array, string & map in Js?
JavaScript for...of
loop allows you to iterate arrays, maps, strings etc. The for...of
loop cannot be used to iterate over an object.
iterable – an iterable object (array, set, strings, etc). element – items in the iterable
for…of with Arrays
// array
const students = ['Javascript', 'JQuery', 'React'];
// using for...of
for ( let element of students ) {
// display the values
console.log(element);
}
for…of with Strings
// string
const message = "Hello";
// using for...of
for (const character of message) {
console.log(character);
}
for…of with Maps
// define Map
const myMap = new Map([
["name", "Alice"],
["age", 30]
]);
for (const [key, value] of myMap) {
console.log(key, value);
}