Asked : Nov 17
Viewed : 18 times
How can I loop through all the entries in an array using JavaScript?
I thought it was something like this:
forEach(instance in theArray)
Where theArray
is my array, but this seems to be incorrect.
Nov 17
TL;DR
Your best bets are usually
for-of
loop (ES2015+ only; spec | MDN) - simple and async
-friendlyforEach
(ES5+ only; spec | MDN) (or its relatives some
and such) - not async
-friendly (but see details)for
loop - async
-friendlyfor-in
with safeguards - async
-friendlySome quick "don't"s:
for-in
unless you use it with safeguards or are at least aware of why it might bite you.map
if you're not using its return value.map
[spec / MDN] as though it were forEach
— but as I write on my blog, that's not what it's for. If you aren't using the array it creates, don't use map
.)forEach
if the callback does asynchronous work and you want the forEach
to wait until that work is done (because it won't).for (const propertyName in theArray) {
if (/*...is an array element property (see below)...*/) {
const element = theArray[propertyName];
// ...use `element`...
}
}
for (let index = 0; index < theArray.length; ++index) {
const element = theArray[index];
// ...use `element`...
}
theArray.forEach(element => {
// ...use `element`...
});
for (const element of theArray) {
// ...use `element`...
}
answered Dec 31
Don't use Array.forEach, use for() instead
Array.ForEach is about 95% slower than for() in for each for Arrays in JavaScript.
So, don't use:
arr.forEach(function (item) {
someFn(item);
})
Use:
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
answered Dec 31
JavaScript Array forEach()
Definition and Usage
The forEach()
method calls a function for each element in an array.
The forEach()
the method is not executed for empty elements.
Syntax
array.forEach(function(currentValue, index, arr), thisValue)
Example 1
Calls a function for each element in fruits:
const fruits = ["apple", "orange", "cherry"];
fruits.forEach(myFunction);
answered Dec 31