DEV Community

Samantha Diaz
Samantha Diaz

Posted on • Updated on

Difference Between 'for...in' and 'for...of' Loop s

This blog summarizes when to use 'for...in' and 'for...of' loops in JavaScript.

Difference

The 'for...in' loop is used for objects. The 'for...of' loop is used on data structures like arrays and strings.

It is possible to use a for in loop with arrays and strings. However, per JavaScript's MDN, the for of loop is preferred for strings and arrays as it returns the index as a number, whereas the for in loop will return the index as a string.

How to remember?

Think about for in loops as being inside an object. Since objects have no order, every item is associated inside it, all together. It's like a purse containing all your items - no order, everything is just inside.

Since arrays and strings have order, think about for of loops as in every item of an array or string. If you were reading a book (array) with chapters (indexes), you would say you're currently "reading chapter 3 of 30 in the book". So, think of it as 'for X index OF an array'.

For...in

For...in loops iterate through an object.

From the MDN Web Doc:

for (const variable in object) {
  statement
}
Enter fullscreen mode Exit fullscreen mode

Examples

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

// "a: 1"
// "b: 2"
// "c: 3"
Enter fullscreen mode Exit fullscreen mode
const obj = { a: 1, b: 2, c: 3 };
for (var i in obj) {
  console.log(i);
}

// "a"
// "b"
// "c"
Enter fullscreen mode Exit fullscreen mode

For...of

For...of loops iterate over an array or string.

From the MDN Web Doc:

for (variable of iterable) {
  statement
}
Enter fullscreen mode Exit fullscreen mode

Examples

const array1 = ['a', 'b', 'c'];

for (const element of array1) {
  console.log(element);
}

// "a"
// "b"
// "c"

Enter fullscreen mode Exit fullscreen mode
const string = 'boo';

for (const value of string) {
  console.log(value);
}
// "b"
// "o"
// "o"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)