JavaScript For Of Loop

for of loop javascript is used to iterate over the iterable objects in javascript.
The iterable objects can be :
- array,set,string etc
- Objects such as NodeList and arguments.
- User defined objects
Syntax
The syntax of for of loop javascript is
variable - elements of the iterable object are assigned to a variable.
iterable - can be arrays,maps,strings etc.
Iterating Over Arrays
for of loop JavaScript can be used to iterate over the elements of an array and manipulate them.
Output
Using the entries() method, we can access the index of the array element with for of loop in javascript.
Output
Iterating Over Strings
for of loop can be used to iterate over each alphabet of the string in javascript.
Output
Iterating Over a Map
for of can be used to iterate over map objects.
Output
Iterating Over a Set
for of can be used to iterate over the unique elements of the set.
Output
Iterating over a DOM Collection
for of loop can be used to iterate over DOM collections like NodeList.
The following programs add a class "Test" to every paragraph directly descendant of an article.
Closing Iterators
break, throw or return statements can be used to abruptly break the for of loop.
Output
Iterating Over Generators
Generators are functions generating an iterable object. for of loop can be used to iterate over generators.
Output
Iterating Over Other Iterable Objects
The for of loop can also be used for iterating over other iterable objects.
for...of Vs for...in
Bothfor...of and for...in are used to iterate over the iterable objects. The difference between for...of and for...in loop is :
| for...of | for...in |
|---|---|
| Iterates over iterable values | Iterates over enumerable object properties |
| Example: for (const value of iterable) {...} | Example: for (const key in object) {...} |
| Accesses values directly | Accesses property keys directly |
| Suitable for iterating arrays and other iterable objects | Not recommended for arrays due to prototype properties and non-numeric keys |
Let's see the difference with an example
Output
Browser Compatibility
Every browser except Internet explorer supports the arrow function.
Some browsers that support arrow functions are
| Browsers | Arrow Function used |
|---|---|
| Chrome | yes |
| Firefox | yes |
| Safari | yes |
| Edge | yes |
| Internet explorer | No |
Conclusion
- for of loop in JavaScript is used to iterate over elements of the iterable object.
- It can iterate over Arrays, strings, maps, sets, and DOM.
- for of loop in JS is the new ES6 feature, which is compatible with every browser except Internet Explorer.