Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 13, 2022 06:50 am GMT

Array.forEach() - for looping through items in an array

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

Original Link: https://dev.to/dillionmegida/arrayforeach-for-looping-through-items-in-an-array-1kmo

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To