Skip to Content
Built Ins.forEach()

.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
  • NodeListsquerySelectorAll returns 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

ParameterWhat it is
elementCurrent item being processed
indexPosition in the array (0-based)
arrayThe original array (rarely needed)
Return valueundefined — always

1. Simple — log each item

const fruits = ['apple', 'banana', 'cherry'] fruits.forEach(fruit => console.log(fruit)) // apple // banana // cherry

2. 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]

  • .map() — same loop but returns a new array
  • .filter() — loop that keeps matching elements
  • for — classic loop with break/continue support
  • Array — the full list of array methods
Last updated on