DEV Community

Anthony Lopez
Anthony Lopez

Posted on

Javascript : The Importance of the forEach() Method

Why This Topic?

For beginners and experts alike, learning a new topic in the field of programming can be quite challenging. It may vary from person to person, but it takes a significant amount of time and effort in order to read, understand, and then use the new material in practice. On top of that, programmers all code differently, and have their own approach, practices and intentions when using said material. For the learning individual, there is a lot of information to intake and thus, can be hard to draw up a starting point.

As like all things, there are golden rules to keep and follow when writing code. These rules consist of following a standard, naming things properly, and being expressive while also avoiding writing god objects and long methods. One particular rule that arguably should be highlighted, stresses that the coder must stay DRY. Being DRY is a software engineering principle which stands for 'Don't repeat yourself'. This principle aims at reducing the repetition of patterns and code duplication, so that the final product would look clean and concise by avoiding redundancy.

But how does one stay DRY? In coding, there is no one distinct way to meet the solution to a problem. One solution can be found in thousands of lines of code, and others can be found as short as maybe hundreds. For beginners especially, it is quite the challenge to find the most optimal route to meet their end goal. When working with arrays, especially those with an obscene amount of values, the beginner may feel taunted to repeat the same lines of code for each and every value in the array. However, that does not have to be the case with the forEach() method available!

But what is the forEach() method? What does it do?

When learning programming, it is important to read, understand, and then being able to write code. Like writing or speaking a language, it is important to convey concisely what it is that the user wants the computer to do. First thing, the syntax for the forEach()method is forEach(callbackFn). The forEach() method executes a provided function once for each array element. In other words, it is an iterative method that calls a provided callbackFn once for each element in the array in ascending-index order. Basically, we take each element in the array as an input for the callbackFn and have said callbackFn perform its task or calculate the value for each input. Hence, it can be understood why it is literally called the forEach() method.

Let's look at an example.

Image description

In the example above, an array is being identified as colors that contains three elements consisting of 'red', 'blue', and 'yellow'. For each of these elements, a message is being output to the console (console.log()). However, there is a way to avoid these lines of repetition and be able to console.log() each element with less lines of code.

Example Code

Image description

Again, here the const colors is being identified as an array. This array has three elements('red', 'blue', and 'yellow'), each one being identified as a 'color'. Using the forEach() method, the function will take each color as an input then console.log() each color in the array of the const colors.

Even in the example of if colors had 1000 elements in the array, the forEach() method would take each of those elements, and execute the provided function. In that scenario, the forEach() would save a significant amount of time by avoiding repeating the same lines of code for each element, and by avoiding repetition, the coder can stay DRY!

However, there are some notes to be aware of on the forEach()
method. A specific note to be discussed is the callbackFn can only invoked in array indexes that have assigned values. The callbackFn will NOT be invoked for empty slots in sparse arrays.

Image description

In the above example, there is a missing value for colors at index 2. The invoked function still takes the inputs for all assigned values but will not be invoked for the empty value at index 2.

Another note on the forEach() method is that while the forEach() method does NOT mutate the array that which it is called, the function provided as callbackFN CAN. However, modifications of the array through that method lead to hard-to-understand code and should be avoided in general cases. That being said, there are many other notes to be explored on the forEach() method but for now, this should be enough information to put this method in practice!

The forEach() method is valuable when it comes to staying DRY, and it is strongly encouraged that when possible, keep your code simple and clean. So the next time you find yourself repeating the same lines of code over and over again, ask yourself 'Can the forEach method be used?', and with your answer hopefully you'll be one more step closer to staying DRY!

Resources
https://www.digitalocean.com/community/tutorials/what-is-dry-development

https://blog.yipl.com.np/7-golden-rules-of-simple-and-clean-code-and-some-more-considerations-slides-e66662af2daf

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#syntax

Top comments (0)