DEV Community

Kevin Rodríguez
Kevin Rodríguez

Posted on • Updated on

11 ways to iterate an array in Javascript

Ahh... Javascript, our beloved language, Its freedom can be either a blessing or a curse.

In this post, we're going to explore 11 different ways (In no specific order) to iterate an array (Not an object) in Javascript.


Let's define our array

People Array

Alright, that's a pretty simple array, let's move on.

1- Trusty old forEach Array.prototype.forEach

The classic forEach array takes two arguments:

1- A function that contains three parameters: the current item, an index, and the original array.
2- A this replacement to be passed to the callback function (It's ignored by arrow functions).

It's the most recommended way to iterate and it's compatible with IE9

forEach loop

2- The for-in loop

This kind of loop usage is discouraged and reserved only for debugging sometimes, yet you might encounter it out there the wild being used in production. It iterates over any custom property defined on an object excluding the default javascript ones. It also works to loop through arrays, but if you define anything on the array prototype, then it's totally going to be iterated too.

For in loop

3 - The for-of loop (ES6)

This is one of the most generous kinds of loops, it's baked in the language specification itself. It's really similar to the for-in loop, but the main difference between both loops is the fact that for-of is used exclusively on collection types (Maps, Sets, Arrays, TypedArrays, NodeLists, etc...). It will avoid object properties and can be used with any object that implements the [Symbol.iterator] Symbol too (See advanced usage).

The main difference to Array.prototype.forEach is the fact that you can use the break keyword to stop the loop and the continue keyword to skip the current iteration.

For of loop

4 - The C Style for loop

This is one of the most used and taught arrays in Compute Science. Its syntax is inherited from the C language and it is composed of three parts:

  • An index initializer
  • A run condition
  • An index modifier that runs at the end of every loop

You can use both break and continue keywords for this kind of loop too.

C Style for loop

5 - The While loop

The while loop is the fastest one (for some reason), it's syntax is really simple:

  • A run condition

If you want to use it to iterate over an array you're going to need to keep track of an index variable too, making it really similar to a C style loop, but with the downside of leaving an index outside of the scope of the loop.

You can use both break and continue keywords for this kind of loop too.

While loop

6 - The Do-while loop

The do-while loop is really similar to the while loop, but it evaluates the run condition at the end of the execution, resulting in it always running the loop at least one time. This makes you need to handle the scenario of an empty array, since accessing an empty array will result in an error. Its syntax is simple too:

  • A run condition

Oh, and you can use both break and continue keywords for this kind of loop too.

Do while loop

7 - The Map method Array.prototype.map

ES5 added three major methods to iterate an array to generate a new array. One of those methods is map.

The map function takes two arguments:

1- A function that contains three parameters: the current item, an index, and the original array.
2- A this replacement to be passed to the callback function (It's ignored by arrow functions).

It shouldn't mutate the original array.

Map loop

8 - The filter method Array.prototype.filter

The filter function is used to evaluate a boolean expression, if true is returned, then the element that is being iterated stays on the new loop, if false is returned then the element is going to be ignored and won't be present on the new array.

Same as the map function, the filter function takes two arguments:

1- A function that contains three parameters: the current item, an index, and the original array.
2- A this replacement to be passed to the callback function (It's ignored by arrow functions).

It shouldn't mutate the original array.

Filter loop

9 - The reduce method Array.prototype.reduce

The reduce function keeps track of a new product and the current element, it also receives a parameter for the initial value of the new product. This can be hard to grasp at the beginning but the more you look at reduce examples, the easier it becomes to you to understand the syntax.

The reduce method gets the following inputs:

1- A function that has the product as the first parameter, and the current element being iterated as a second parameter, a third parameter which is the current element index and the last parameter that provides access to the original array.
2- An initial value to be used for the product.

The reduce method is typically used to synthesize a whole array into one value, like performing a sum for example.

ES6 Reduce loop

10 - String-Array join method Array.prototype.join

The join method has something in common with the last method we introduced (reduce): It does generate a single output from an array, a string to be more specific, and it can only run on string-based arrays.

It has an only input: A separator string to be used.

Join method

11 - ES2018 for await of

This is one of the newest features introduced to javascript, it allows us to place an await in our for of loops, allowing them to iterate on promises and asynchronous values (See async generator functions).

You can use for await of along with async generator functions to specify loops that will wait for the current promise being iterated to be completed, or you can use it to await on an array of promises (You should probably use Promise.all for this though).

For await of

Another example:

For await of promise array


Extras and honorable mentions:

ES2019 Flat method Array.prototype.flat

It iterates through the main array to find nested arrays and brings the values contained on any nested array to the top level.

You can specify how deep in the array structure you want to go to bring the array values to the top level.

Array Flat

ES2019 Flatmap method Array.prototype.flatMap

It's exactly the same as map followed by a flat. You can use this one to flatten the product of a map that produces nested arrays.

Array flat map

(Thanks to Pablo Obando for these suggestions) 😄

Recursion

You can use recursion to iterate an array, thanks @nombrekeff !

Recursion in functional terms is when a function is able to call itself, looping trough the code. This has some advantages:

1- You can customize your loop as much as you want.
2- Functional approach.
3- Really helpful when you're dealing with other kind of structures like trees or circle lists.

But be careful, javascript does have a maximum call stack size, this means on every iteration a call is registered in the call stack, and if there are way too many calls, then you'll overflow the call stack, causing an exception, also, recursive calls are slower too because of this behavior.

You can even create a mix of a C Style loop and a forEach loop!

Let's go ahead and define a recursive function to replicate the functionality of Array.prototype.forEach:

Recursive function loop


So, there are probably lots of ways out there to iterate an array on javascript, like inverse do-while loops. or any of the other not-so-popular Array.prototype methods like every, some, reduceRight or flatMap, but here are some of the most popular ways to iterate an array in javascript 🚀

Top comments (10)

Collapse
 
shankarsridhar profile image
Shankar Sridhar

That was a good read, Kevin :)

I think there is a typo in section for for await of:
tough => though

(You should probably use Promise.all for this tough).
Enter fullscreen mode Exit fullscreen mode
(You should probably use Promise.all for this though).
Enter fullscreen mode Exit fullscreen mode
Collapse
 
misterkevin_js profile image
Kevin Rodríguez

Thanks for that one! I completely missed this typo 🥺

Collapse
 
joeattardi profile image
Joe Attardi

I think map/filter/reduce were added in ES5, not ES6 😀but this is a great article! The versatility of JS!

Collapse
 
misterkevin_js profile image
Kevin Rodríguez • Edited

Thanks!, corrected!

Collapse
 
pamprog profile image
PamProg

Hello, really nice article :)
You just made a little typo in your first sentence :D
"it's freedom can be either a blessing or a curse" => its*

Collapse
 
misterkevin_js profile image
Kevin Rodríguez

Thanks ! 🙏🏼

Collapse
 
nombrekeff profile image
Keff

Nice article, I would also mention recursion :) It's also a good way of iterating an array in some scenarios

Collapse
 
misterkevin_js profile image
Kevin Rodríguez

Thanks! Added

Collapse
 
alexandre_gilardeau_bf466 profile image
Alexandre Gilardeau

whats' the name of the theme you are using ??thank you very usefull

Collapse
 
misterkevin_js profile image
Kevin Rodríguez

Synthwave 84'