This content originally appeared on DEV Community and was authored by Dillion Megida
This article is the fourth of the Array Method series. Here, I'll explain the forEach
array method.
What is the forEach method?
The forEach
method is very similar to the map
method. The difference is that the map
method loops through each item and returns a new array, while the forEach
method only loops and returns nothing.
The forEach
method of arrays is a higher-order function that loops through each item in the array and performs some operations on the items.
As a higher-order function, it takes a function as an argument. During the loop, this function receives an item (and its index position in the array), and you can do whatever you want with that item.
Syntax of the forEach method
someArray.forEach(function(item, index, array) {
// something with item and/or index
})
The item
argument is the item being looped on.
The index
argument is the position in the array. For example, the first item has an index of 0, and the second, 1.
The array
argument is the array itself.
Without the forEach method
The forEach
method is a declarative abstracted method that literally "does something for each item". Here's an example showing how you can loop through an array without this method:
const array = [...]
for(let i = 0, i < array.length, i++) {
const item = array[i]
// do something with item
}
This loop approach is similar to what the forEach
method does behind the scenes.
With the forEach method
For example, you want to concatenate strings in an array to one string. Here's how:
const array = ["apple", "banana", "cashew", "pawpaw"]
let string = "I bought "
array.forEach(function(item, index) {
if (index === 0) {
string += item
} else if (index === array.length - 1) {
string += ` and ${item}`
} else {
string += `, ${item}`
}
})
console.log(string)
// I bought apple, banana, cashew and pawpaw
This content originally appeared on DEV Community and was authored by Dillion Megida
Dillion Megida | Sciencx (2022-04-13T06:50:39+00:00) Array.forEach() – for looping through items in an array. Retrieved from https://www.scien.cx/2022/04/13/array-foreach-for-looping-through-items-in-an-array/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.