DEV Community

Alaa Mkbs
Alaa Mkbs

Posted on

The difference between for...of and for...in loops in JavaScript

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...of gives you the actual elements
  • for...in gives you the indices (as strings)
const data = ['apple', 'banana', 'cherry'];

for (let item of data) {
    console.log(item);
}
// Output:
// apple
// banana  
// cherry
Enter fullscreen mode Exit fullscreen mode
const data = ['apple', 'banana', 'cherry'];

for (let index in data) {
    console.log(index);
}
// Output:
// 0
// 1
// 2
Enter fullscreen mode Exit fullscreen mode

With Strings:

  • for...of gives you each char in the word
  • for...in gives 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
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
alexmustiere profile image
Alex Mustiere

You can use for...of on a object if you use Object.entries().

const person = { name: 'John', age: 30, city: 'NYC' };
for (const [k, v] of Object.entries(person)) { console.log(k, v); }
// Output: name John, age 30, city NYC
Enter fullscreen mode Exit fullscreen mode