Which one is better for iterating through things in JavaScript: .map(), .forEach(), or a for loop?

If I had to choose it would be .forEach(), however are there situations where a for loop is better, .map(), maybe even a while loop?

‘Better’ can be a subjective term. If we had none of the new iterators of ES6 we could still get by. JS went for more than a dozen years without them. Demand is what brought them into the fold.

We’ll never lose the need of for loops.

const a = [1,2,3,4,5,6,7,8,9]
let b = []
for (let x of a) {
    b.push(x ** 2)

The above loop maps the new array over the old one so they each have corresponding elements. b is the squares of a. It is obvious which iterator to reach for to achieve the same result, and it is explicit, to boot.

b = a.map(x => x ** 2)

It would be rather clumsy to do the above using forEach.

b = []
a.forEach(x => b.push(x ** 2))

It might look neater than the for loop, but it is nothing like map for simplicity.

Hmm… I see. So really it just depends on the situation you are using them for.
By the way, is there a difference of doing:

for ( let i =0; i > arr.length; i++){


for (let x of arr){

Do they work the same?

1 Like

No. The first one iterates a numeric sequence, in this case integers and then uses the current value as an index if working with an iterable (arr) inside the loop, or a counter if simply counting the number of times through the loop. The direction can be either left to right or right to left.

The second one is read-only and polls the values in the array. It iterates the entire array, from left to right.

Both of the above can have a breaking condition if we wish to interrupt flow at a certain value. Array.forEach() cannot be given a breaking condition.

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.