JavaScript for…of Loop
8 April 2025 | Category: JavaScript
The for...of
loop is used to iterate over iterable objects like arrays, strings, maps, sets, and more.
It gives you the values directly, not the indexes or keys.
✅ Syntax
for (let item of iterable) {
// Code to run
}
iterable
can be an array, string, set, etc.item
is the current value in the loop.
🔢 Example: Loop Through an Array
let fruits = ["apple", "banana", "cherry"];
for (let fruit of fruits) {
console.log(fruit);
}
Output:
apple
banana
cherry
🔤 Looping Through a String
let word = "Hello";
for (let letter of word) {
console.log(letter);
}
Output:
H
e
l
l
o
✅ Better Than for...in
for Arrays
Unlike for...in
, which gives you indexes, for...of
gives you values — cleaner and more readable.
for...in
vs for...of
on arrays:
let colors = ["red", "green", "blue"];
for (let i in colors) {
console.log(i); // Outputs: 0, 1, 2
}
for (let color of colors) {
console.log(color); // Outputs: red, green, blue
}
🧠 Can You Use it on Objects?
❌ No, you can’t use for...of
directly on plain objects.
let obj = {name: "John", age: 30};
// ❌ This will cause an error:
// for (let x of obj) {
// console.log(x);
// }
✅ Instead, convert the object to an array using Object.keys()
, Object.values()
, or Object.entries()
:
let person = {name: "Alice", age: 22};
for (let value of Object.values(person)) {
console.log(value);
}
🧾 Summary
Feature | for...of Loop |
---|---|
Used for | Arrays, strings, sets, maps |
Output | Values |
Use on object? | Not directly |
Clean for loop | ✅ Best for arrays/strings |