JavaScript for...of Loop
Iterate through values of iterable objects
🔄 What is the for...of Loop?
The for...of loop iterates over the values of iterable objects like arrays, strings, and more. It's perfect when you need the actual values, not the indexes.
// Basic for...of loop
const fruits = ['apple', 'banana', 'orange'];
for (const fruit of fruits) {
console.log(fruit);
}
Output:
for...of vs for...in
for...of (Values)
Gets the actual values
for (const value of array) {
console.log(value);
}
for...in (Keys)
Gets the property names/indexes
for (const key in array) {
console.log(key);
}
Strings
Iterate through characters
for (const char of "Hello") {
console.log(char);
}
Sets & Maps
Works with modern collections
const set = new Set([1, 2, 3]);
for (const num of set) {
console.log(num);
}
🔹 Array Iteration
The most common use of for...of is with arrays:
const colors = ['red', 'green', 'blue'];
// Simple iteration
for (const color of colors) {
console.log(`I like ${color}`);
}
// With index using entries()
for (const [index, color] of colors.entries()) {
console.log(`${index}: ${color}`);
}
Output:
🔹 String Iteration
for...of works great with strings, treating them as arrays of characters:
const message = "Hello";
for (const letter of message) {
console.log(letter);
}
// Practical example: count vowels
const text = "JavaScript";
let vowelCount = 0;
for (const char of text.toLowerCase()) {
if ('aeiou'.includes(char)) {
vowelCount++;
}
}
console.log(`Vowels found: ${vowelCount}`);
Output:
🔹 Working with Objects
Objects aren't directly iterable, but you can use Object methods:
const person = {
name: 'John',
age: 30,
city: 'New York'
};
// Iterate over values
for (const value of Object.values(person)) {
console.log(value);
}
// Iterate over keys
for (const key of Object.keys(person)) {
console.log(key);
}
// Iterate over key-value pairs
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`);
}
Output:
🔹 Practical Examples
Real-world uses of for...of loops:
🔸 Processing Shopping Cart
const cart = [
{ name: 'Laptop', price: 999 },
{ name: 'Mouse', price: 25 },
{ name: 'Keyboard', price: 75 }
];
let total = 0;
for (const item of cart) {
console.log(`${item.name}: $${item.price}`);
total += item.price;
}
console.log(`Total: $${total}`);