ā¤ Like
šŸ”– Save
šŸ”— Share
@thedevspaceio
@thedevspaceio

JavaScript Array forEach()

@thedevspaceio

šŸ” JavaScript Array forEach() Cheatsheet

forEach() runs a function for every element in an array, making it a clean way to perform side effects without a traditional loop.

āœ… Basic syntax āœ… Side effects āœ… forEach vs map āœ… Using index and original array āœ… Breaking out early

#javascript #arrays #foreach #iteration #loops #webdev #frontend #coding #tips


Basic syntax

forEach() calls a function once for every element in an array.

It does not return a value and does not mutate the array unless you do so inside the callback.

js
array.forEach((element, index, array) => {
  // side effect
});
ParameterDescription
elementThe current element being processed.
indexThe index of the current element.
arrayThe original array forEach was called on.

Side effects

Unlike map(), forEach() is commonly used to perform side effects rather than to transform data.

Use forEach() when you want to perform an action for each element.

js
const users = ["Ada", "Grace", "Alan"];
 
users.forEach((user) => {
  console.log(`Hello, ${user}`);
});

Or update an external variable.

js
const scores = [10, 20, 30];
let total = 0;
 
scores.forEach((score) => {
  total += score;
});
 
console.log(total); // 60

forEach vs map

MethodReturnsBest for
forEach()undefinedSide effects
map()A new arrayTransforming data
js
const numbers = [1, 2, 3];
 
// āœ… side effect
numbers.forEach((n) => console.log(n));
 
// āœ… transformation
const doubled = numbers.map((n) => n * 2);

Using index and original array

Access the index while iterating.

js
const items = ["a", "b", "c"];
 
items.forEach((item, index) => {
  console.log(`${index}: ${item}`);
});
// 0: a
// 1: b
// 2: c

Use the original array for context.

js
const numbers = [2, 4, 6];
 
numbers.forEach((n, i, arr) => {
  console.log(`${n} is ${i === arr.length - 1 ? "last" : "not last"}`);
});

Breaking out early

You cannot break or continue inside forEach(). Use a for...of loop instead.

js
const numbers = [1, 2, 3, 4, 5];
 
for (const n of numbers) {
  if (n === 3) break;
  console.log(n);
}
// 1
// 2

Full-Stack AI Developer Roadmap

From HTML & CSS to working with AI models, all in one structured roadmap.

@thedevspaceio
www.thedevspace.io