8 Ways to Loop Through an Array in JavaScript

Lincoln W Daniel
Dec 2 · 12 min read

In many programming languages, one of the most basic data structures is an array. With an array, you add elements for accessing at a later time, state, in your program. You can access each element by directing accessing its index, position, in the array, or you can access all of the elements by looping through the array. In this article, we take a look at the many ways you can loop through an array in JavaScript.

Warning: If you’re still obligated to build for Internet Explorer 🤮, you should check with a source to ensure the newer and more convenient of these methods will work.

This story was originally published in 1Liner.dev.

1. for Statement

const names = ['Lincoln', 'Daniel', 'Tabitha', 'McLeod']for (let i = 0; i < names.length; i++) {
const currentName = names[i]
console.log(currentName, 'is at index', i)
}

That prints the following:

Lincoln is at index 0
Daniel is at index 1
Tabitha is at index 2
McLeod is at index 3

Notice that indices start at 0. This is the case in most, if not all, programming languages. That means that the first element in an array is positioned at the first index. From there, each subsequent element can be accessed in order by adding 1 to the previously accessed index. That’s exactly what we do with the for statement.

The for statement allows us to loop over an array starting from any index and ending at another index. We can start at a low index and increment upwards to a higher index, or do the opposite; in most cases, you'll want to start from a low index and loop upwards. If you want to loop downwards, you can do something like this:

for (let i = names.length - 1; i >= 0; i--) {
const currentName = names[i]
console.log(currentName, 'is at index', i)
}

Using the names array from above, that loop would print the following:

McLeod is at index 3
Tabitha is at index 2
Daniel is at index 1
Lincoln is at index 0

The for statement consists of three statements: statements one, two, and three.

for (statement 1; statement 2; statement 3) {
// code block to be executed
}

Statement one is used to initialize a counter. You can initialize multiple counters, but, usually, you’ll just initiate a single counter. In our first case, for (let i = 0; i < names.length; i++), we initiated a variable called i as our counter and started it at index 0.

Statement two defines a condition by which to continue running the looping. In most cases, you use this statement to evaluate the state of the counter. If this statement evaluates to true, the loop will run again; otherwise, it won't run again. This condition is checked before every loop is ran, including the first loop. That means if the condition is never true, the loop will never run.

In our first case, we specified our condition to check whether our counter is less than the length of the array because we only want to loop from index 0 to the last index in the array, which is the length of the array minus 1. This condition is true for index 0, 1, 2, and 3. After the fourth loop, the counter is at 4. Because 4 is not less than the length of the array, which is also 4, the condition does not evaluate to true, and the loop does not run again.

Statement three is executed after each loop. This statement is normally used to increment or decrement the counter, depending on which direction you’ve decided to loop. In our first case, we do i++ to increment the counter by one because we are looping upwards from the first index in the array, 0. In our second case, we do i-- to decrement the counter by one because we are looping downward from the last index in the array.

Each of these statements are optional, but you must always include the semicolon for each statement.

How to break out of a for loop

Now that we know how to loop through an array using the for statement, let's discuss how we can terminate our loop by breaking out when we've found what we're looking for.

The break statement can be used to break out of a for and while loop. This is how we can use it in a for loop to stop looping once we've found the element we were looking for:

const names = ['Lincoln', 'Daniel', 'Tabitha', 'McLeod']for (let i = 0; i < names.length; i++) {
const currentName = names[i]
console.log(currentName, 'is at index', i)
if (currentName === 'Tabitha') {
console.log('We found her!')
break
}
}

That prints the following:

Lincoln is at index 0
Daniel is at index 1
Tabitha is at index 2
We found her!

After we’ve found the name “Tabitha” in the array, we break out of the loop. That’s why “McLeod is at index 3” is not printed this time as it was the first time we looped over this array without a break statement. However, if the conditional statement currentName === 'Tabitha' never evaluated to true, we would have never broke out of the loop.

2. while Statement

The while statement is much like the for statement, but it only takes a single conditional statement, which it checks before each loop. The difference here is you're responsible for what would be statement one and statement three in a for loop.

In its simplest form, the while statement takes the following form:

while (condition) {
// code block to be executed
}

However, as I mentioned above, you need a way to eventually have the condition evaluate to false in order to end the loop. That is the purpose of statement three in a for loop; it increments or decrement the counter so that the condition in statement two eventually fails to evaluate to true, effectively ending the loop. So in practice, a while statement takes a form with more resemblance to the for statement:

// statement 1
while (condition) { // statement 2
// code block to be executed

// statement 3
}

Let’s rewrite our for statement from above in the form of a while statement to loop over the same names array:

const names = ['Lincoln', 'Daniel', 'Tabitha', 'McLeod']let i = 0 // statement 1while (i < names.length) { // statement 2
const currentName = names[i]
console.log(currentName, 'is at index', i)

i++ // statement 3
}

That prints the same thing as the first for loop from above:

Lincoln is at index 0
Daniel is at index 1
Tabitha is at index 2
McLeod is at index 3

In that code, we start by initiating a counter, i, to 0; that would be statement one in a for loop. Next, we run our while loop on the condition that the counter's value is less than the length of our names array; that is the same statement two condition as we had in our first for loop. In each iteration of our while loop, we access the element at the current index of the array using our counter. Finally, at the end of each iteration, we increment our counter by 1 in before our while statement's condition is checked again. The point here is that the while statement works much like a for statement. That means we can also break out of a while loop the same way we did in our for loop:

while (i < names.length) {
const currentName = names[i]
console.log(currentName, 'is at index', i)

if (currentName === 'Tabitha') {
console.log('We found her!')
break
}
i++
}

As you should expect by now, that prints the following:

Lincoln is at index 0
Daniel is at index 1
Tabitha is at index 2
We found her!

That’s the same output as we had when we broke out of our for loop earlier in this article. Isn't that neat?

You could also use a return statement to break out of the loop, but code after the while statement won't run, as should be expected when you return from a function.

How to skip a loop iteration

What if we want to skip an iteration of our loop given a condition? We can do that by using the continue statement, which works in both the while and for statements. If we want to skip the code block for the third loop, index 2, which would print, "Tabitha is at index 2", we just need to execute a continue statement when an appropriate condition evaluates to true:

while (i < names.length) { // statement 2
if (i === 2) {
console.log('Skipping the name at index', i)

i++
continue
}
const currentName = names[i]
console.log(currentName, 'is at index', i)

i++
}

That prints the following:

Lincoln is at index 0
Daniel is at index 1
Skipping the name at index 2
McLeod is at index 3

continue pretty much means "skip the rest of this code block and try to loop again." Notice that we still need to increment our counter before continuing. Otherwise, when we "try to loop again", we would evaluate our condition with the same counter value; this would go on forever as an infinite loop; in most cases, infinite loops are bad.

There’s also the do...while statement, which is much like the while statement except it runs the code block before evaluating the condition. That means, unlike with the while statement, your code block will always run at least one.

Let’s move on to more concise ways to loop through an array.

3. for...of Statement

The for...of statement works much like a regular for statement, but it does a lot of the boilerplate work for you. You can use this statement to loop over any iterable object, including but not limited to strings, arrays, array-like objects (e.g., arguments or NodeList), Map, and Set.

The for...of statement takes the following form:

for (variable of iterable) {
statement
}

For “variable”, you must declare a variable as you would anywhere else in JavaScript. This variable will then be set to an element in the array as we loop through. On the first iteration, your variable will be set to the first element in the array. On the second, it will be set to the second element. That pattern will continue for as long as the loop continues, which would be for as long as the iterable has more elements to access or until we break out of the loop. The “iterable”, in our case, will be an array.

Let’s loop over our names array again using this fancy for...of statement:

for (const currentName of names) {
if (currentName === 'Tabitha') {
console.log('Skipping', currentName)
continue
}
console.log(currentName)
}

That prints the following:

Lincoln
Daniel
Skipping Tabitha
McLeod

In that example, we used the continue statement to skip "Tabitha". We can also break out of this loop the same way we do in a for or while loop.

4. Array.prototype.forEach() Method

Now we’re getting into the methods built specifically for looping through arrays. These methods can be called directly on your array to loop through it. Let’s start with forEach().

To loop through the elements of an array and execute a function, you can call the forEach() method on the array. The function you provide has the following signature: callback(currentValue, currentIndex, sourceArray).

Let’s use this method to print each element of our names array in a single string:

const names = ['Lincoln', 'Daniel', 'Tabitha', 'McLeod']let greeting = 'Hi'names.forEach((name, currentIndex, sourceArray) => {
if(currentIndex === sourceArray.length - 1) {
greeting += ` and ${name}.`
} else {
greeting += ` ${name},`
}
})
console.log(greeting)

That prints the following sentence: Hi Lincoln, Daniel, Tabitha, and McLeod. We used the currentIndex and sourceArray arguments to check if we were on the last element in the array; when that was true, we knew we could end the list and sentence with "and" and a period respectively. This is usually the easiest way to loop through an array when you don't need to break out of the loop.

If you do need to break out of the loop but don’t want to go back to using the for or while loop, there's another array method for you.

5. Array.prototype.some() Method

The Array.prototype.some() method works much like the forEach() method with one caveat: your callback function for each loop needs to return true or false. Why? Because this method is usually used to check if some (or at least one) of your array's element meets a certain criteria, as defined by your condition.

The function you provide has the following signature: callback(currentValue, currentIndex, sourceArray). The some() method returns true if your provided function returns a truthy value for at least one of the elements in your array; otherwise, it'll return false.

Say we want to check if any of the strings in our names array contain two a's. We can do the following using the some() method:

const names = ['Lincoln', 'Daniel', 'Tabitha', 'McLeod']let nameWith2Asconst foundNameWith2As = names.some((name) => {
const has2As = name.indexOf('a') !== name.lastIndexOf('a')
if (has2As) {
nameWith2As = name
}

console.log(name)

return has2As
})
if (foundNameWith2As) {
console.log('We found a name with two "a" characters:', nameWith2As)
} else {
console.log('We did not find a name with two "a" characters.')
}

That prints the following:

Lincoln
Daniel
Tabitha
We found a name with two "a" characters: Tabitha

Notice that it “McLeod” was never printed. That’s because as soon as your function returns a truthy value, the looping ends. It’s like an automatic break statement.

There’s also the every() method for arrays. It works much like the some() method, but it returns true only if your provided function returns a truthy value for all of the elements in your array. Note that it will always return true if your array is empty.

What if you want to loop through your array to find all the elements that meet a certain criteria. You could accomplish this in many ways using the methods we’ve already explored, but a very convenient method exists for that exact purpose.

6. Array.prototype.filter() Method

The Array.prototype.filter() method comes in handy when you want to create a new array of only the elements that meet your desired criteria. You call filter() on your array with the same function as the other array methods we've seen. In your function, you need to return true if the current element meets the criteria and false if it doesn't.

Let’s create a new array of all the names from our names array that have an "L" or "l":

const names = ['Lincoln', 'Daniel', 'Tabitha', 'McLeod']let namesWitHL = names.filter((name, currentIndex, sourceArray) => {
return name.toUpperCase().includes('L')
})
console.log(namesWitHL)

That prints the new array: [ 'Lincoln', 'Daniel', 'McLeod' ].

7. Array.prototype.map() Method

What if you want to loop through your array and create a new array from the elements of your original array. You can use the Array.prototype.map() method. The map() method accepts a function with the same signature as the function from the methods we've explored.

const names = ['Lincoln', 'Daniel', 'Tabitha', 'McLeod']let reversedNames = names.map((name, currentIndex, sourceArray) => {
const reversedName = name.split('').reverse().join('')

return reversedName
})
console.log(reversedNames)

That prints the new array of each name in the original array reversed: [ 'nlocniL', 'leinaD', 'ahtibaT', 'doeLcM' ]

Your function can return anything you want it to. Just remember that whatever you return will be added to your new array.

8. Array.prototype.reduce() Method

Finally, there’s the very powerful Array.prototype.reduce() method which seemingly combines everything we've discussed thus far. You can use it to loop through the elements of your array, skipping elements, applying a filter, and ultimately return a single value, which can be a new array, object, function, number, string, or any other datatype in JavaScript. It's a wonderful method. The only thing you can't do is break out of the loop without throwing an error, which you probably wouldn't want to do.

We’ve already created an entire guide to the reduce() method, so let's just take a look at a quick example:

const myFriends = [
{name: 'Lincoln', age: 20},
{name: 'Daniel', age: 23},
{name: 'Tabitha', age: 24},
{name: 'McLeod', age: 24},
]
console.log(myFriends.reduce((str, friend, index, friends) => {
if (index === 0) {
return `${str} ${friend.name} (${friend.age})`
} else if (index !== friends.length - 1) {
return `${str}, ${friend.name} (${friend.age})`
} else {
return `${str}, and ${friend.name} (${friend.age}).`
}
}, 'My friends are'))

That prints the following sentence:

My friends are Lincoln (20), Daniel (23), Tabitha (24), and McLeod (24).

Isn’t that just beautiful? You can also reduce backwards, from the end of the array to the front, right to left, by using the reduceRight() method instead.

Conclusion

Creating and manipulating arrays is an essential part of JavaScript programming. It’s important that you understand how to loop through an array efficiently in various scenarios. In this article, we’ve covered more than eight different ways to iterate through the elements of an array. You should be well equipped now to manipulate any array you come across to solve any problem you’re faced with.

Happy programming!

1Liner

Explaining code 1 line at a time.

    Lincoln W Daniel

    Written by

    My passion is in developing software to enable people to accomplish their goals more efficiently. Author @JavaForHumans.com. Creator of @Smedian.com

    1Liner

    1Liner

    Explaining code 1 line at a time.

    Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
    Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
    Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade