Introduction
The for…of loop lets go through each item in a collection one by one. The for…of loop in JavaScript is used to iterate over iterable objects. This includes arrays, strings, nodeLists, and HTMLCollections. The syntax of this loop is similar to the for/in the loop. The object must be iterable to be used with this loop.
Syntax
for…of loop represnts by the following syntax.
for (variable_name of iterable_objects) { // javascript code }
Parameters
- variable_name is a variable that holds the current item from the iterable in each iteration. i.e let, var, and const javascript keywords.
- iterable_objects is the collection you want to loop through. It contains the array, sets, map, and data as an argument.
Return
The loop displays data from arrays, sets, or maps. In other words, it shows the values from these collections as output.
Example of for…of loop
Loop through a string name “CodeSpeedy”.
const word = 'CodeSpeedy'; for (const char of word) { console.log(char); }
Output
C o d e S p e e d y
Conclusion
The for…of loop in JavaScript is a simple and powerful tool for looping through collections like arrays, sets, maps, and strings. It makes your code easy to read and write by directly accessing the values in these collections without needing to manage index numbers.