DEV Community

Victoria Lima De Carvalho
Victoria Lima De Carvalho

Posted on • Edited on

Using the forEach() method in JS

The forEach() method is one of the most effective ways to go through all the elements in an array. With this method, you can perform specific actions on each element in the array.

A key benefit of using forEach() is that it allows you to work with each element without needing to create a new array. This method is useful when you need to update a variable, print something to the console, or modify the DOM.
One of the most important things to remember, is that forEach() doesn’t return a new array.

Another advantage of using the forEach() method, is that it doesn’t require the index of each item. It’s a simpler and faster way to loop through an array. So when you're writing you code, you can know that the forEach() method will iterate through the arrays without needing to have a starting index.

In arrays with empty slots, forEach() will ignore them. A regular for loop will still process those empty slots, even if they don’t contain any values in them. This is another way that using forEach() can be beneficial.

One thing to keep in mind is that you cannot stop a forEach() loop once it starts. So, if you need to break out of the loop early, or stop the loop from continuing at a certain determined point, forEach() won’t work for you.

Another important fact to remember about this method, is that forEach() only works with functions that run synchronously. This means that it won’t wait for promises or asynchronous functions to finish before it starts the method of iterating through the elements in the array. So remember to be mindful of that when combining forEach() with asynchronous code.

Here’s an example of how forEach() is typically written:

array.forEach(callback(currentValue, index, array), thisArg)
Enter fullscreen mode Exit fullscreen mode

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

https://www.geeksforgeeks.org/difference-between-foreach-and-for-loop-in-javascript/

https://www.w3schools.com/jsref/jsref_foreach.asp

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more