The difference between for...of and for...in loops in JavaScript
Source: Dev.to
When working with JavaScript, understanding the difference between for...of and for...in loops is crucial for writing clean, efficient code. While they might look similar, they serve different purposes and work with different data structures.
Arrays
for...ofgives you the actual elements.for...ingives you the indices (as strings).
const data = ['apple', 'banana', 'cherry'];
// for...of – iterates over values
for (let item of data) {
console.log(item);
}
// Output:
// apple
// banana
// cherry
// for...in – iterates over keys (indices)
for (let index in data) {
console.log(index);
}
// Output:
// 0
// 1
// 2
Strings
for...ofiterates over each character.for...initerates over the character indices (as strings).
const text = "hello";
// for...of – characters
for (let char of text) {
console.log(char);
}
// Output: h e l l o
// for...in – indices
for (let index in text) {
console.log(index);
}
// Output: 0 1 2 3 4
Objects
for...ofdoes not work directly with plain objects (it throws an error).for...initerates over an object’s enumerable property keys.
const person = { name: 'John', age: 30, city: 'NYC' };
// for...in – keys and values
for (let key in person) {
console.log(key, person[key]);
}
// Output:
// name John
// age 30
// city NYC