After years of web development, do you still find yourself mixing up for...in and for...of loops in JavaScript? If you’re tired of Googling every time you need to loop through a collection, I’ve got a handy memory trick to help you effortlessly remember when to use each loop statement.

a) “index in, object of”

b) ‘i’n -> not ‘i’terables, o’f -> not ‘o’bjects

for…in loops over enumerable property names of an object.

for…of (new in ES6) does use an object-specific iterator and loops over the values generated by that.

Code Snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const colorsArr = ['Red', 'Blue', 'Green', 'White'];

for (const color in colorsArr) {
	console.log(color);
}

// Output
0
1
2
3

Almost everytime I expect that value of colors will be printed instead of index values. To get the values we have to modify the loop as below

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const colorsArr = ['Red', 'Blue', 'Green', 'White'];

for (const color in colorsArr) {   // it makes more sense
	console.log(colorsArr[color]);  // to rename color to index
}

// Output
Red
Blue
Green
White

Using for...of loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const colorsArr = ['Red', 'Blue', 'Green', 'White'];

for (const color of colorsArr) {
	console.log(color);
}

// Output
Red
Blue
Green
White

Difference

for...infor...of
Applies toEnumerable PropertiesIterable Collections
Use with Objects?YesNo
Use with Arrays?Yes, but not advisedYes
Use with Strings?Yes, but not advisedYes

I will not go much into the differences; you can read the blog JavaScript for…of vs for…in Loops (A Complete Guide)

However, I prefer to use for...of almost everywhere. Infact for looping over properties of an object too; I prefer for...of loop like below:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
const person = {
  name: 'Manish Prasad',
  age: 37,
  job: 'developer'
};

for (const key of Object.keys(person)) {
  console.log(key + ': ' + person[key]);
}

// Output

name: Manish Prasad
age: 37
job: developer

Conclusion:

In this post, I have not dived much deep into the differences. I prefer to use for...of loop almost everytime. Another big advantage of preferring for...of loop is early exiting.

✨ Thank you for reading and I hope you find it helpful. I sincerely request for your feedback in the comment’s section.