JavaScript for...of Loop
Subject: JavaScript
The for...of loop in JavaScript allows you to iterate directly over the values of iterable objects like arrays, strings, maps, sets, and more. It’s more readable and efficient when you don’t need the index or key.
Syntax
variable: Local variable that holds the current value.iterable: Any object implementing the iterable protocol.
Example 1: Looping Through an Array
Example 2: Looping Through a String
Example 3: Looping Through a Set
Example 4: Looping Through a Map
for...of vs for...in
| Feature | for...of | for...in |
|---|---|---|
| Iterates Over | Values of iterables | Keys of objects |
| Use Case | Arrays, strings, sets, maps | Plain objects |
| Returns | Value | Property name (key) |
| Recommended For | Value-based iteration | Object property iteration |
Key Takeaways
for...ofis ideal for value-based iteration on iterable objects.- Works with: arrays, strings, sets, maps, arguments, etc.
- Does not work with plain objects.
- Use destructuring when looping over Maps or arrays of pairs.
- Prefer
for...ofwhen you don't need an index, just the value.