How to Use for of Loop in JavaScript: Syntax and Examples
Use the
for of loop in JavaScript to iterate over iterable objects like arrays, strings, or sets. It automatically accesses each element in order without needing an index. The syntax is for (const item of iterable) { /* code */ }.Syntax
The for of loop syntax is simple and easy to read:
const item: declares a variable to hold the current element.of iterable: specifies the iterable object to loop over (like an array or string).- The loop body runs once for each element in the iterable.
javascript
for (const item of iterable) { // code to run for each item }
Example
This example shows how to use for of to print each fruit in an array:
javascript
const fruits = ['apple', 'banana', 'cherry']; for (const fruit of fruits) { console.log(fruit); }
Output
apple
banana
cherry
Common Pitfalls
Common mistakes include trying to use for of on non-iterable objects like plain objects, or confusing it with for in which loops over keys instead of values.
Also, avoid modifying the iterable inside the loop as it can cause unexpected behavior.
javascript
const obj = {a: 1, b: 2}; // Wrong: for of does not work on plain objects // for (const item of obj) { // console.log(item); // } // Correct: use for in to loop over keys for (const key in obj) { console.log(key, obj[key]); }
Output
a 1
b 2
Quick Reference
- Use for of to loop over arrays, strings, maps, sets, and other iterables.
- Do not use for of on plain objects (use for in instead).
- Variable declared in the loop holds the current element.
- Loop stops after the last element.
Key Takeaways
Use for of to iterate over iterable objects like arrays and strings easily.
for of gives you direct access to each element without using indexes.
Do not use for of on plain objects; use for in for object keys instead.
Avoid changing the iterable inside the for of loop to prevent bugs.
The syntax is simple: for (const item of iterable) { /* code */ }.