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

Published: (December 4, 2025 at 05:59 PM EST)
2 min read
Source: Dev.to

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...of gives you the actual elements.
  • for...in gives 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...of iterates over each character.
  • for...in iterates 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...of does not work directly with plain objects (it throws an error).
  • for...in iterates 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
Back to Blog

Related posts

Read more »