JavaScript .forEach Loop
For-each is one of the basic yet fundamental ways of looping over arrays in Javascript. One of the main things that stood out to me in the beginning was the copious amount of ways of looping(.forEach) over arrays which, I now know is catered to the programmers own preferred/personalized style.
.forEach and what does it do?
The forEach method within Javascript executes a callback function once for each array element.
Syntax
This is the syntax for a forEach loop. As we can see, we have an array which is iterated(an object that can be used to loop through collections) and calls all the elements one by one which are then assigned to “(example)” which then we can perform any operations on the “(example)”.
Parameters
The forEach method passes a callback function for each element of an array together with the following parameters:
- Current Value (required) — The value of the current array element
- Index (optional) — The current element’s index number
- Array (optional) — The array object to which the current element belongs
Return:
undefined. Always.
Get Leon Wong’s stories in your inbox
Join Medium for free to get updates from this writer.
To not get the loops confused “Filter and Map” returns an array whereas forEach returns undefined
Conditions/Rules of forEach
- forEach executes the callback function once for each array element
- forEach always returns as undefined
- forEach does not change the array, but the callback can if programmed to
- forEach is not chain-able like Map and Filter
- The elements processed by forEach is set before the first invocation of the callback function
- Elements appended to the array after forEach started are not visited by the loop
- Elements that are deleted before being visited by the loop are not visited
- If elements that are already visited are removed form the array during the iteration, later elements will be skipped
- forEach does not execute the callback for the array elements without values
Summary
The forEach method passes a callback function for each element of an array. forEach can easily be confused with Map and Filter, just remember that forEach will always return undefined. One big bonus that I forgot to mention was the difference between for-loop and forEach. When using for-loop the user needs to create the full template getting the length of the array, initializing, incrementing, and assigning value to i whereas forEach does not require that, the user simply just has to define a callback.






