In this JavaScript lesson we are going to learn about JavaScript For of Loop, so for .. of is an enhanced version of for .. in and forEach loops, and it is a feature in JavaScript ES6.
Now let’s create an example, if you see in this example we have an array of names, now we want to iterate over this array, for iterating we need to use for loop, and you will see the result in the output.
1 2 3 4 5 |
const names = ["Parwiz", "John", "Ahmad", "Karim"] for(let i = 0; i < names.length; i++) { console.log(names[i]) } |
But in ES6 JavaScript we have a shorter version of for loop that is called for of loop.
1 2 3 4 5 6 |
const names = ["Parwiz", "John", "Ahmad", "Karim"] for(let name of names) { console.log(name) } |
Also you can get the index of an array by using entries() function of for of loop.
1 2 3 4 5 6 |
const names = ["Parwiz", "John", "Ahmad", "Karim"] for(let name of names.entries()) { console.log(name) } |
JavaScript For of Loop Features
As we already mentioned that The for…of loop is feature in JavaScript that is used to iterate over iterable objects such as arrays, strings and maps. these are some features of for…of loop in JavaScript.
- Looping Over Arrays: The
for...of
loop can be used to iterate over arrays.
1 2 3 4 5 6 7 8 9 10 |
const numbers = [1, 2, 3]; for (const number of numbers) { console.log(number); } // Output: // 1 // 2 // 3 |
In this example, the for…of loop is used to iterate over each element in the numbers array and log it to the console.
- Looping Over Strings: The
for...of
loop can be used to iterate over the characters in a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const message = "Hello, world!"; for (const char of message) { console.log(char); } // Output: // H // e // l // l // o // , // // w // o // r // l // d // ! |
In this example, the for…of loop is used to iterate over each character in the message string and log it to the console.
- Looping Over Maps: The
for...of
loop can be used to iterate over the key-value pairs in map.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
const myMap = new Map(); myMap.set("a", 1); myMap.set("b", 2); myMap.set("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 is used to iterate over each key value pair in the myMap
map and log it to the consol.
In result we can say that for...of
loop is a powerful tool for iterating over iterable objects in JavaScript and can simplify code in many situations.