What is for...of?
for...of is a loop that iterates over values of an iterable object.
An iterable is something that can be looped over, like:
-
Arrays
-
Strings
-
Maps
-
Sets
-
Typed Arrays
-
Generator objects
-
argumentsobject
Think of it as: “Give me each value in this collection, one at a time.”
Syntax
for (const value of iterable) {
// use the value
}
-
iterable→ something loopable (like an array or string) -
value→ each value from that iterable
Basic Example with Array
const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
console.log(fruit);
}
// apple
// banana
// cherry
Here:
-
for...ofdirectly gives values (not indexes) -
Cleaner than a
forloop if you don’t need the index.
Example with String
const word = "Hello";
for (const char of word) {
console.log(char);
}
// H
// e
// l
// l
// o
It loops through each character.
Example with Map
const map = new Map([
["name", "Gagan"],
["role", "Developer"]
]);
for (const [key, value] of map) {
console.log(key, "=>", value);
}
// name => Gagan
// role => Developer
Example with Set
const set = new Set([1, 2, 3, 3]);
for (const value of set) {
console.log(value);
}
// 1
// 2
// 3 (no duplicates)
Comparing for...in vs for...of
| Feature | for...in |
for...of |
|---|---|---|
| Loops over | Keys (property names) | Values |
| Works on | Objects (and arrays, but not ideal) | Iterables (arrays, strings, maps…) |
| Use case | Loop through object properties | Loop through iterable values |
| Includes inherited properties? | Yes | No |
Why use for...of?
✅ Simpler syntax for values
✅ Works naturally with iterables
✅ Avoids index-to-value conversion in arrays
✅ Cleaner than forEach if you want to use break or continue
When NOT to use for...of
-
On plain objects — they are not iterable by default:
const obj = { a: 1, b: 2 };
for (const value of obj) { // ❌ TypeError
console.log(value);
}
Instead, convert to an array first:
for (const value of Object.values(obj)) {
console.log(value);
}
Extra Tip — Getting index in for...of
for...of doesn’t give indexes directly, but you can use entries():
const colors = ["red", "green", "blue"];
for (const [index, color] of colors.entries()) {
console.log(index, color);
}
// 0 red
// 1 green
// 2 blue
Cheat Sheet
-
for...in → keys/properties
-
for...of → values of iterables
-
Arrays, strings, maps, sets → ✅ works with
for...of -
Plain objects → ❌ not iterable without conversion
No comments:
Post a Comment