forEach - Array functions

iamashusahoo

Ashutosh

Posted on August 23, 2020

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)
})
💖 💪 🙅 🚩
iamashusahoo
Ashutosh

Posted on August 23, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Mastering the For Loop in JavaScript
javascript Mastering the For Loop in JavaScript

September 22, 2023

JS Test #3: try/catch
javascript JS Test #3: try/catch

December 18, 2022

using pseudocode as a beginner - why and how
javascript using pseudocode as a beginner - why and how

September 14, 2022

Method chaining in Javascript
javascript Method chaining in Javascript

September 13, 2022

Demystifying Fetch()
javascript Demystifying Fetch()

July 12, 2022