DEV Community

Cover image for forEach: The infinite loop with boundaries.
jrob112
jrob112

Posted on • Updated on

forEach: The infinite loop with boundaries.

Wash...
As in all things there is a beginning. How did it all start? Well, there was an array and an opportunity to access each individual elements of that array. A direction of which way to go.

How often is it available? What are we to do with it? How can we effect each element? For loops allowed all this to happen.
for(let i=0;i<array.length;i++){
(start);(stop);(increment)
['What can we do with what we have?']
}

...Are we there yet?

Rinse...
For whatever purpose you are trying to achieve with your code, the forEach method is to be used when all elements of an array must be accessed in ascending order. A higher-order function is a function that takes one or more functions as arguments, or returns a function as its result. For example, forEach is a higher-order function that takes a callback function and executes it once for each array element. Also, forEach is a method on the array itself, so it can be called on any array using the dot notation. Unlike most other higher-order functions, forEach does not return a new collection. Instead, it goes through the original collection and allows its items to be used in repetitive operations and tasks. The forEach() method returns "undefined". Whether you are adding them all together, multiplying, pushing them into a separate array, or passing a function that is executed on each element in the array.*****BUT, there is not a return value for this method.
array.forEach(element => {output.push(element)}

Repeat...
An excellent way to reduce bugs, is to use the forEach method. Because of scope ownership, the forEach method prevents contamination into other aspects of your code. Although, it is not a method that would be used for specialized application, it is very helpful in time management and less key strokes. The more that gets done with less amount of energy used has got to be better, right?

               *Extra Credit-Sources*
          Mozilla - https://developer.mozilla.org
Enter fullscreen mode Exit fullscreen mode

Top comments (0)