Source: Loop (for each) over an array in JavaScript
for (const element of theArray) {
// ...use `element`...
}
forEach
(ES5+ only; spec | MDN) (or its relativessome
and such) - notasync
-friendly (but see details)
theArray.forEach(elem, index => {
// ...use `elem`...
});
- a simple old-fashioned
for
loop -async
-friendly
for (let index = 0; index < theArray.length; ++index) {
const element = theArray[index];
// ...use `element`...
}
- (rarely)
for-in
with safeguards -async
-friendly
for (const propertyName in theArray) {
if (/*...is an array element property (see below)...*/) {
const element = theArray[propertyName];
// ...use `element`...
}
}
Continue reading »