Js Loop For Of in JavaScript
? JavaScript for...of Loop
The for...of loop is used to iterate over iterable objects like arrays, strings, maps, sets, and more. It directly gives you the values of the iterable instead of the index.
? Syntax
for (const element of iterable) { // code to execute using element}? Example: Loop through an Array
const fruits = ["apple", "banana", "cherry"];for (const fruit of fruits) { console.log(fruit);}Output:
applebananacherry? Loop through a String
const word = "Hello";for (const char of word) { console.log(char);}Output:
Hello? Benefits of for...of
Easier syntax when you only need the values (no index)
Works on any iterable (arrays, strings, sets, maps, NodeLists, etc.)
Cleaner and less error-prone than traditional
forloops for iteration
? Difference Between for...of and for...in
for...of | for...in |
|---|---|
| Iterates over values | Iterates over keys/indexes |
| Works on iterables like arrays, strings | Works on objects’ enumerable properties |
| Use to get actual data | Use to get property names or indexes |
Would you like an example of for...in or more advanced iteration?