Main difference between [for…of] and [for…in] when working with arrays:
const arr = ['a', 'b', 'c'];
// for...of — values
for (const value of arr) {
console.log(value); // 'a', 'b', 'c'
}
// for...in — indices
for (const index in arr) {
console.log(index); // '0', '1', '2' (strings!)
}Imagine you have a shelf with books. [for…of] is like going through the books themselves, while [for…in] is like going through the shelf numbers! 📚🔢
Works with the array elements themselves:
const fruits = ['apple', 'banana', 'orange'];
// Get values directly
for (const fruit of fruits) {
console.log(fruit);
}
// 'apple'
// 'banana'
// 'orange'
// Works with numbers too
const numbers = [1, 2, 3];
for (const num of numbers) {
console.log(num); // 1, 2, 3
}Works with “slot names” (indices):
const fruits = ['apple', 'banana', 'orange'];
// Get indices (as strings!)
for (const index in fruits) {
console.log(index); // '0', '1', '2' (strings!)
console.log(fruits[index]); // 'apple', 'banana', 'orange'
}
// Indices are strings!
console.log(typeof index); // 'string'const numbers = [10, 20, 30];
// for...of — numbers
for (const num of numbers) {
console.log(num + 1); // 11, 21, 31
}
// for...in — strings!
for (const index in numbers) {
console.log(index + 1); // '01', '11', '21' (strings!)
}const sparse = ['a', , 'c']; // Missing element
// for...of — iterates everything, including gaps
for (const value of sparse) {
console.log(value); // 'a', undefined, 'c'
}
// for...in — only existing indices
for (const index in sparse) {
console.log(index); // '0', '2' (no '1'!)
}// ✅ When you need elements themselves
const items = ['pen', 'pencil', 'eraser'];
for (const item of items) {
console.log(`I have: ${item}`);
}// ✅ When you need indices
const items = ['pen', 'pencil', 'eraser'];
for (const index in items) {
console.log(`At position ${index}: ${items[index]}`);
}const arr = ['a', 'b', 'c'];
// ❌ Mistake — think for...in gives values
for (const item in arr) {
console.log(item); // '0', '1', '2' — indices, not values!
}
// ✅ Correct — use for...of for values
for (const item of arr) {
console.log(item); // 'a', 'b', 'c' — values
}const arr = [10, 20, 30];
// ❌ Mistake — indices are strings!
for (const index in arr) {
console.log(arr[index] + 5); // Works
console.log(index + 5); // '05', '15', '25' — strings!
}
// ✅ Correct — convert to number
for (const index in arr) {
console.log(+index + 5); // 5, 6, 7 — numbers
}Understanding the difference between [for…of] and [for…in] helps iterate arrays correctly! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪