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);
}
2 Comments
tlover tonet
December 28, 2024Hi I am so grateful I found your website, I really found you by mistake, while I was searching on Askjeeve for something else, Anyways I am here now and would just like to say thank you for a tremendous post and a all round enjoyable blog (I also love the theme/design), I don’t have time to look over it all at the minute but I have bookmarked it and also included your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the excellent work.
Anirban Poddar
February 10, 2025Thank you for your valuable comments