11 ways to iterate an array in Javascript
Tags: javascript, arrays, loops, iterators
Published: 2020-03-10 04:13:59

---
title: 11 ways to iterate an array in Javascript
published: true
description: Javascript arrays are pretty interesting, let's explore some ways to iterate/loop through an array.
tags: javascript, arrays, loops, iterators
---

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](https://dev-to-uploads.s3.amazonaws.com/i/f45kk1tz0vxz5ydt8k32.png)


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](https://dev-to-uploads.s3.amazonaws.com/i/l50sxqn6qwuu02jkmy3z.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/9o26au5tbwtckg0p6crf.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/ws2205ipldgoa7qfhyfi.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/tpowf4k2h786ehxq8qrf.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/089t51fw4qn7f4s1jnfk.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/tm0djggvl7bgwe455bk9.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/f8nvtdb2q91ox51n6sk4.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/h3ajvkn87zhp8n1vd1qz.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/8gvt68fqbnnwvfxseh1t.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/j3ue396x2tcgfk1nt4uf.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/lj025vq1q09ixql2y8ix.png)

Another example:

![For await of promise array](https://dev-to-uploads.s3.amazonaws.com/i/s5rdqij3n1827vg6wg97.png)

---

# 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](https://dev-to-uploads.s3.amazonaws.com/i/n4cfyvyve1pir351n7zg.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/i/0gkcwvdrhtln7qsfqg0x.png)

(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](https://dev-to-uploads.s3.amazonaws.com/i/dq3mofy0eviu4zxhasn0.png)

---

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 🚀