.forEach()
Array method that calls a function on every element. Unlike .map(), it doesn’t return anything — it’s for side effects only.
When to use it
- Side effects — logging, DOM updates, sending requests
- Iteration — when you don’t need a new array back
- NodeLists —
querySelectorAllreturns a NodeList that has.forEach()
Anatomy
array.forEach((element, index, array) => {
// element — the current item
// index — its position (0-based)
// array — the original array (rarely used)
// no return value — forEach always returns undefined
})At a glance
| Parameter | What it is |
|---|---|
element | Current item being processed |
index | Position in the array (0-based) |
array | The original array (rarely needed) |
| Return value | undefined — always |
1. Simple — log each item
const fruits = ['apple', 'banana', 'cherry']
fruits.forEach(fruit => console.log(fruit))
// apple
// banana
// cherry2. Intermediate — update DOM elements
const items = document.querySelectorAll('.item')
// NodeList supports forEach directly
items.forEach((el, i) => {
el.style.animationDelay = `${i * 100}ms` // stagger animations
el.classList.add('visible')
})3. Advanced — batch side effects with index
const users = [
{ name: 'Alice', email: 'alice@test.com' },
{ name: 'Bob', email: 'bob@test.com' },
]
// build rows into an existing table body
const tbody = document.querySelector('tbody')
users.forEach((user, i) => {
const row = tbody.insertRow()
row.className = i % 2 === 0 ? 'even' : 'odd' // zebra striping
row.insertCell().textContent = user.name
row.insertCell().textContent = user.email
})Gotchas
Can’t break out early
// forEach runs the callback for every element — no way to stop
[1, 2, 3, 4].forEach(n => {
if (n === 3) return // this skips the rest of THIS iteration, not the loop
console.log(n) // 1, 2, 4 — skipped 3 but still ran 4
})
// use a for...of loop if you need to break
for (const n of [1, 2, 3, 4]) {
if (n === 3) break // actually stops the loop
console.log(n) // 1, 2
}Don’t use forEach when you need a result
// forEach returns undefined — the mapped array is lost
const result = [1, 2, 3].forEach(n => n * 2)
result // undefined
// use .map() when you need the transformed array back
const result = [1, 2, 3].map(n => n * 2)
result // [2, 4, 6]Related
Last updated on