I’m sure you might have come across map() and forEach() while working with** JavaScript.** If you have ever worked with Arrays but there are some of my new details about these two functions that we tend to miss out let’s try to brush our basics with the help of this Article.

Functionality Of forEach()

Understanding the working of forEach() is simple it is a function defined on the array.prototype and hence is available to all JavaScript Arrays.

ForEach, It’s a function that we can call on any** Array Object.** It takes another function as an input. When forEach is called an array, JavaScript takes the array items one by one and calls that function for each of them.

Functionality of forEach()

Functionality of ForEach Function.

Most of us do not pay attention, to this part with JavaScript also pass the** Index** of that Array Item and also the Original Array when it calls the function forEach item though, most of the time we are only interested in the** Value** of the item. The function executes for each item and then finally undefined is written to the caller that’s all about it.

In this example, we are trying to call the forEach Function and we passed it a logArray function, the logArray function does nothing but Console.log the value of each of the array element, for which it is making use of the element and the index value pass to it.

newArr = [2,3,4,7].forEach(logArray){
console.log('array[' + index + '] = ' + element);
}

Image for post

Result of Example, Step By Step.

Notice that When the forEach loop completes running the newArr variable gets the value undefined, As that is what ForEach returns every time it runs.

#javascript-tips #javascript #web-development

Should I Use map() or forEach() in JavaScript?
35.50 GEEK