Array.forEach
Run a side effect once for every item. forEach does not build a new array.
Use forEach when you want to do something with each
item (append a row, update the DOM). Its return value is always
undefined — use map when you need a new array.
Before (source array)
After (DOM side effects)
Important JavaScript
const players = ["Ava", "Ben", "Cara"];
// Side effects only — return value is undefined
players.forEach(function (name) {
const li = document.createElement("li");
li.textContent = name;
list.appendChild(li);
});
// Second argument is the index
players.forEach((name, index) => {
console.log(index + ": " + name);
});
const leftover = players.forEach((name) => name.toUpperCase());
// leftover === undefined (use map to transform)