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.
With Arrays:
-
for...ofgives you the actual elements -
for...ingives you the indices (as strings)
const data = ['apple', 'banana', 'cherry'];
for (let item of data) {
console.log(item);
}
// Output:
// apple
// banana
// cherry
const data = ['apple', 'banana', 'cherry'];
for (let index in data) {
console.log(index);
}
// Output:
// 0
// 1
// 2
With Strings:
-
for...ofgives you each char in the word -
for...ingives you the indices (as strings)
const text = "hello";
for (let char of text) {
console.log(char); // h, e, l, l, o
}
for (let index in text) {
console.log(index); // 0, 1, 2, 3, 4
}
With Objects:
- for ... of doesn't work directly with plain objects (This would throw an error)
- for ... in gives you key value for each element
const person = { name: 'John', age: 30, city: 'NYC' };
// for...in works with objects
for (let key in person) {
console.log(key, person[key]);
}
// Output: name John, age 30, city NYC
Top comments (1)
You can use
for...ofon a object if you useObject.entries().