For-each over an array in JavaScript

Asked : Nov 17

Viewed : 27 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.

javascript arrays loops foreach iteration 
3 Answers

TL;DR

Your best bets are usually

  • a for-of loop (ES2015+ only; spec | MDN) - simple and async-friendly
  • forEach (ES5+ only; spec | MDN) (or its relatives some and such) - not async-friendly (but see details)
  • a simple old-fashioned for loop - async-friendly
  • (rarely) for-in with safeguards - async-friendly

Some quick "don't"s:

  • Don't use for-in unless you use it with safeguards or are at least aware of why it might bite you.
  • Don't use map if you're not using its return value.
    (There's sadly someone out there teaching 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.)
  • Don't use 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


Login and Submit Your Answer
Browse other questions tagged  javascript  arrays  loops  foreach  iteration or ask your own question.