What is the difference between JavaScript's for...in, for...of and forEach?

for...in
for...in
is used to iterate over all enumerable properties of an object, including inherited enumerable properties. This iteration statement can be used with arrays, strings or plain objects, but not with Map
or Set
objects.
for (let prop in ['a', 'b', 'c'])
console.log(prop); // 0, 1, 2 (array indexes)
for (let prop in 'str')
console.log(prop); // 0, 1, 2 (string indexes)
for (let prop in {a: 1, b: 2, c: 3})
console.log(prop); // a, b, c (object property names)
for (let prop in new Set(['a', 'b', 'a', 'd']))
console.log(prop); // undefined (no enumerable properties)

Refactoring for...in loops to avoid ESLint warnings
ESLint is a really useful tool, but sometimes it gets in the way. Learn how to refactor code to get rid of a common warning.
for...of
for...of
is used to iterate over iterable objects, iterating over their values instead of their properties. This iteration statement can be used with arrays, strings, Map
or Set
objects, but not with plain objects.
for (let val of ['a', 'b', 'c'])
console.log(val); // a, b, c (array values)
for (let val of 'str')
console.log(val); // s, t, r (string characters)
for (let val of {a: 1, b: 2, c: 3})
console.log(prop); // TypeError (not iterable)
for (let val of new Set(['a', 'b', 'a', 'd']))
console.log(val); // a, b, d (Set values)

Array index in for...of loops
Did you know you can get the index of an array item in a JavaScript for...of loop? Learn how with this bite-sized tip.
Array.prototype.forEach()
Finally, forEach()
is a method of the Array
prototype, which allows you to iterate over the elements of an array. While Array.prototype.forEach()
only iterates over arrays, it can access both the value and the index of each element while iterating.
['a', 'b', 'c'].forEach(
val => console.log(val) // a, b, c (array values)
);
['a', 'b', 'c'].forEach(
(val, i) => console.log(i) // 0, 1, 2 (array indexes)
);

Iterate over array in reverse
Learn how to execute a function for each element of an array, starting from the last one.