The JavaScript array.forEach() method
The forEach() method runs a function once for each element in an array — handy for side effects like logging, updating the DOM or pushing to another structure. Unlike map(), it returns undefined, so use it when you care about doing something per element, not about collecting a result.
Overview
forEach() is the array world's version of a simple loop: it calls your function once for every element, in order. You use it when you want to do something with each item — print it, add it to the page, send it somewhere — rather than transform the array into a new one. It always returns undefined.
The callback receives the element, its index and the whole array, just like map() and filter(). The difference is purely intent: if you find yourself building up a result array inside a forEach(), that's a sign map() or reduce() would say it better.
One thing to know going in: you can't break out of a forEach() early, and return only skips to the next element. If you need to stop partway — say, on the first match — a for...of loop or some() is the right tool. Also note that forEach() doesn't wait for async callbacks, so for sequential awaiting, use for...of.
Syntax
array.forEach(callbackFn)
array.forEach(callbackFn, thisArg)
array.forEach((element, index, array) => {
// do something with element
})
Parameters
The array.forEach() method accepts the following parameters.
| Parameter | Description |
|---|---|
callbackFn |
Function run for each element. Receives (element, index, array). Its return value is ignored. |
thisArg |
Optional. A value to use as this inside the callback. |
Example
<ul id="list" style="font:15px system-ui,sans-serif"></ul>
<script>
const todos = ['Write code', 'Test it', 'Ship it'];
const list = document.getElementById('list');
todos.forEach((todo, i) => {
const li = document.createElement('li');
li.textContent = (i + 1) + '. ' + todo;
list.appendChild(li);
});
</script>
Best practices
- Use
forEach()for side effects; use map() when you actually want a new array back. - Need to stop early?
forEach()can'tbreak— switch to a for...of loop or some(). - For sequential
awaitinside the loop, usefor...of—forEach()won't pause for promises. - Skip the rest of the current iteration with an early
return; it moves on to the next element rather than ending the loop.
Frequently asked questions
What is forEach() used for in JavaScript?
undefined.How do I break out of a forEach() loop?
What is the difference between map() and forEach()?
forEach() returns nothing. Use map() for the result, forEach() for the action.Does forEach() work with async/await?
async callback to finish before the next one starts. For sequential awaiting, use a for...of loop.