Iterating in JavaScript
There are multiple ways to loop in JavaScript, some common ones being:
forloop:for (let i=0; i < something.length; i++) { ... }forEachon an array:array.forEach((arrayItem) => { ... })for...ofon iterable (ES6):for (const arrayItem of array) { ... }
Advantages of for...of over forEach
- Works on any iterable object
- Allows for flow control within (can
awaitorreturnearly)
for...of vs for...in
The key takeaway is to use for...of and avoid for...in (unless including inherited properties is desired)
The introduction of for...of allows for iterating over the values of an iterable object. Previous to its introduction, it was common to see something like the following:
var obj = { a: 1, b: 2 };
for (var key in obj) {
// Skip inherited properties
if (!obj.hasOwnProperty(key)) {
continue;
}
console.log(obj[key]);
}
This required extra logic to avoid including inherited properties on the object.
Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over.
The for...in statement iterates over the enumerable properties of an object.
The for...of statement iterates over values that the iterable object defines to be iterated over.
MDN: for...of: Differences between for...of and for...in