DEV Community 👩‍💻👨‍💻


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.


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...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("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++) {

// after

Top comments (0)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!