There are at least 3 different ways to loop over arrays in JavaScript. The three we will go over in this article are the
- forEach
- for of
- 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
- You can not break out of the loop, it has to go through every element in the array.
- It is a higher order function
- 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}`)
}