3 different ways to loop through arrays in JavaScript in 2023

There are at least 3 different ways to loop over arrays in JavaScript. The three we will go over in this article are the

  1. forEach
  2. for of
  3. for loop

Using forEach to loop through an array

The forEach takes a callback function that is executed for element of the array. The callback function’s first argument is the element of the array.

const myArray = ["First", "Second", "Third"]

myArray.forEach(function(myElement, index, array) {
  console.log(`My Element is ${myElement}, index is ${index}, and array is {$array}`

Couple things to note about forEach

  1. You can not break out of the loop, it has to go through every element in the array.
  2. It is a higher order function
  3. The first argument is the array element, the second is the index, and the 3rd is the array itself

Using for of to loop through an array

Using the for of loop, we can loop through the array with

const myArray = ["First", "Second", "Third"]

for (const [i, myElement] of myArray) {
  console.log(`My Element is ${myElement}, index is ${i}`)

Looping through an array with a for loop

And using just a simple for loop, we can do

const myArray = ["First", "Second", "Third"]

for (let i = 0; i < myArray.length; i++) {
  console.log(`My Element is ${myarray[i]}, index is ${i}`)


Bash Loop Examples

For i in 1-100 do

Basically count to 100 and perform an operation each time i increases.

for ((i=1; i<=100;i++))
  echo $i

for loop 1 liner

for ((i=1; i<=100;i++)) do echo $i ; done

While true (Execute forever)

Handy if you just want a script to run and repeat the same thing over and over again. Doesn't stop till you kill it.

while true
  echo "Repeat till infinity"
  sleep 1

While command is true

The following will execute the loop as long as the command in the () returns true. Once it returns false, it'll stop the loop

while (fping incredigeek.com | grep alive); 
  echo alive
  sleep 1