DEV Community

Cover image for JavaScript forEach() & Building Elements
Jessica Vaughn
Jessica Vaughn

Posted on

JavaScript forEach() & Building Elements

I recently built my first single-page project using JavaScript - an application called Wufr. Users can swipe left or right on their favorite dog images pulled from an API. By swiping right, users can save images of dogs into their favorites. If you are interested in reading more about this project or utilizing Wufr, please check out my Wufr GitHub repository. You can also check out the walkthrough here.

As I considered the best method to render the user's favorite dogs, the JavaScript forEach() method stood out as a great option to iterate through the array of favorite dogs created by each user when they 'swiped right' on their favorite dogs and then pass a callback function to render each dog image.

For Loop vs. forEach()

For Loop

For loops are excellent for iterating over arrays and elements and executing a block of code. A break statement allows the code to 'break' out of the loop and stop the effect of the looping code at a designated point. For loops are more efficient performance-wise than forEach(), but generally require more code. If you're looking to execute a block of code multiple times, especially if the number of times is known, consider using a for loop. You can read more about for loops here.

Image description

forEach()

The forEach() method iterates through each element in an array and passes a callback function on each element. forEach() is a great option if you are looking for a method to iterate through each item one time. As forEach() accepts a callback function, developers can write with more brevity than when using a traditional for loop, where each line of code must be enumerated. forEach() returns undefined, even if the callback function passed in has a return statement, therefore forEach() is typically utilized to achieve side effects rather than to return anything.

forEach() iterates through elements in an array in ascending order by index. The method requires an array or element to be passed in and allows the starting index position to be specified. The forEach() method does not mutate the original array, but does allow for callback functions to mutate the array. The initial length of the array is saved as forEach() is called, therefore the method will not iterate past the initial length of the array even if the callback function mutates the original array.

Image description

forEach() & Building Elements

I decided to use forEach() to render favorite dog images on Wufr. This allowed me to manipulate the DOM by creating a new image element, set image attributes, add an event listener to each dog as it was created, and finally to append the dog image to the DOM in the favorites container, all within a callback function. With a small amount of code, I was able to execute this for each favorite dog image in my array.

Image description

In this case, I wanted my code to run the exact same way for each dog in my dogs array. The total number of elements in my dogs array is dependent on how many favorite dogs the user had saved, and since I did not need to utilize a break statement to exit my block of code at some point, forEach() seemed like the best fit for the job.

Troubleshooting forEach() in Wufr

While building Wufr, I initially set my favorite dogs variable to an empty array. Then I called forEach() on the array and passed in my callback function with an additional step - trying to push a new dog into my dogs array. I spent quite a bit of time trying to figure out why forEach() was not rendering any dogs images until I had added a second dog to my dogs array, meaning I had to add a dog to my favorites a second time to see the first dog rendered. The functionality was as if my application was rendering one dog behind each dog I swiped right on. I was not receiving an error message, but my application was not functioning as expected with push() as part of the forEach() callback function.

After reading through the MDN documentation on forEach() I realized forEach() was saving the initial length of my array, and even though my callback function was mutating the array, this mutated array was not being passed into forEach() until the second time I called forEach() and the array already had a length of 1 element. In order for forEach() to iterate and pass a callback function to elements in the array, the array must have at least one element in it.

After creating a second function to handle a post request to my db.json file and push my new favorite dog into my dogs array, forEach() rendered all of my favorite dogs as expected.

Closing Thoughts

forEach() is an incredibly useful JavaScript method which should be considered when iterating through arrays and passing some side effects to each element. It allows the developer to shorten their syntax and to clearly demonstrate what is happening in their code through utilizing a callback function. As you decide whether to use this method, keep in mind that forEach() is a non-destructive method and you will need to utilize other functions to handle any changes to the array you are iterating through.

Top comments (0)