DEV Community

Ashutosh
Ashutosh

Posted on

forEach - Array functions

Looping is an essential part of project development. We have the basic for loop to iterate through the code to execute a certain set of codes. forEach and map functions help in iterating through a function for each element present in the array.

forEach

Syntax : 

array.forEach(callback(item, index, array), thisVar)

array - contains the list of elements for which we want to run the callback function
item - (*optional*) Each item is passed to the function as an argument.
index - (*optional*) Contains the index of the element that is passed as an argument.
thisVar - (*optional*) Used to set the context for the given function, upper scope. It is not needed if we use the arrow functions

Note - The return value is "undefined"

There is no way to stop or break a forEach() function. If we want such behavior this can be achieved using simple for loop, for...in, for...of, or other array functions like every(), some(), find(), findIndex().

Also, we need to take care forEach doesn't account for asynchronous functions and thus it is better to avoid it during API calls.

No operation for uninitialized values

const array = ["Hello","World",,"skipped uninitialized value"]
let numCallbackRuns = 0

arraySparse.forEach((element) => {
  console.log(element)
  numCallbackRuns++
})

console.log("numCallbackRuns: ", numCallbackRuns)

// Hello
// World
// skipped uninitialized value
// numCallbackRuns: 3
// the missing value between "World" and "skipped uninitialized value" didn't invoke the callback function. Even if it would have been a "", it would have a count

Converting for loop to forEach

const shop = ['banana', 'rice', 'pulses']
const copyItems = []

// before
for (let i = 0; i < shop.length; i++) {
  copyItems.push(shop[i])
}

// after
shop.forEach(function(item){
  copyItems.push(item)
})

Top comments (0)