Mastering the forEach Method in JavaScript Arrays


JavaScript's array methods are powerful tools for manipulating and iterating over data. Among them, the forEach() method stands out for its simplicity when you need to perform an action on every element in an array without creating a new one. Unlike map() or filter(), forEach() doesn't return anything—it's all about side effects, like logging, updating external variables, or modifying the array in place.

In this blog post, we'll break down the syntax of forEach(), explore its parameters, and dive into 30 programming examples complete with code and outputs. These examples range from basic to more advanced scenarios to help you grasp its versatility. All examples are written in modern JavaScript (ES6+) and can be run in any browser console or Node.js environment.

What is the forEach() Method?

The forEach() method executes a provided callback function once for each element in an array, in order. It's non-mutating by default (it doesn't change the original array unless you explicitly do so inside the callback), and it always returns undefined. This makes it ideal for tasks like rendering UI elements, logging data, or accumulating results in an external variable.

Key points:

  • It skips over empty slots in sparse arrays.
  • It doesn't work on non-array iterables (use Array.from() if needed).
  • It's synchronous and doesn't support async/await directly (use for...of for that).

Syntax

array.forEach(callback(currentValue, index, array), thisArg);

Parameters Explained:

  • callback: A function to execute on each element. It can take up to three arguments:
    • currentValue(required): The current element being processed.
    • index (optional): The index of the current element.
    • array (optional): The array forEach() was called upon.
  • thisArg (optional): A value to use as this when executing the callback (useful with arrow functions or binding).

If no callback is provided, it throws a TypeError.

Basic Examples: Logging and Simple Operations

Example 1: Logging Array Elements

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

Output:

apple
banana
cherry

Example 2: Logging with Index

const numbers = [10, 20, 30];
numbers.forEach((num, index) => console.log(`Index ${index}: ${num}`));

Output:

Index 0: 10
Index 1: 20
Index 2: 30

Example 3: Accessing the Full Array

const colors = ['red', 'green', 'blue'];
colors.forEach((color, index, arr) => console.log(`${color} is at position ${index} in [${arr}]`));

Output:

red is at position 0 in [red,green,blue]
green is at position 1 in [red,green,blue]
blue is at position 2 in [red,green,blue]

Example 4: Using thisArg with a Regular Function

const obj = { multiplier: 2 };
[1, 2, 3].forEach(function(num) {
  console.log(num * this.multiplier);
}, obj);

Output:

2
4
6

Example 5: Skipping Empty Slots in Sparse Arrays

const sparse = [1, , 3];
sparse.forEach(num => console.log(num));

Output:

1
3

Numerical Operations: Summing, Averaging, and More

Example 6: Calculating Sum

const nums = [5, 10, 15];
let sum = 0;
nums.forEach(num => sum += num);
console.log(sum);

Output:

30

Example 7: Finding Maximum Value

const values = [8, 3, 11, 5];
let max = -Infinity;
values.forEach(val => { if (val > max) max = val; });
console.log(max);

Output:

11

Example 8: Counting Even Numbers

const evens = [2, 4, 5, 6, 7];
let count = 0;
evens.forEach(num => { if (num % 2 === 0) count++; });
console.log(count);

Output:

3

Example 9: Doubling Each Element (In-Place Mutation)

const doubles = [1, 2, 3];
doubles.forEach((num, index, arr) => arr[index] = num * 2);
console.log(doubles);

Output:

[ 2, 4, 6 ]

Example 10: Accumulating Product

const factors = [2, 3, 4];
let product = 1;
factors.forEach(factor => product *= factor);
console.log(product);

Output:

24

String Manipulations

Example 11: Uppercasing Strings

const words = ['hello', 'world'];
words.forEach((word, index, arr) => arr[index] = word.toUpperCase());
console.log(words);

Output:

[ 'HELLO', 'WORLD' ]

Example 12: Concatenating Strings

const parts = ['Java', 'Script'];
let full = '';
parts.forEach(part => full += part);
console.log(full);

Output:

JavaScript

Example 13: Counting Vowels

const sentence = ['a', 'e', 'i', 'o', 'u'];
let vowelCount = 0;
sentence.forEach(char => { if ('aeiou'.includes(char)) vowelCount++; });
console.log(vowelCount);

Output:

5

Example 14: Reversing Each String

const strs = ['abc', 'def'];
strs.forEach((str, index, arr) => arr[index] = str.split('').reverse().join(''));
console.log(strs);

Output:

[ 'cba', 'fed' ]

Example 15: Logging String Lengths

const names = ['Suresh', 'Sam', 'Stanley'];
names.forEach(name => console.log(name.length));

Output:

6
3
7

Working with Objects and Arrays of Objects

Example 16: Logging Object Properties

const users = [{ name: 'John' }, { name: 'Jane' }];
users.forEach(user => console.log(user.name));

Output:

John
Jane

Example 17: Updating Object Properties

const items = [{ price: 10 }, { price: 20 }];
items.forEach(item => item.price += 5);
console.log(items);

Output:

[ { price: 15 }, { price: 25 } ]

Example 18: Collecting Keys from Objects

const objArray = [{ a: 1 }, { b: 2 }];
let keys = [];
objArray.forEach(obj => keys.push(...Object.keys(obj)));
console.log(keys);

Output:

[ 'a', 'b' ]

Example 19: Filtering Objects into New Array

const people = [{ age: 25 }, { age: 17 }, { age: 30 }];
let adults = [];
people.forEach(person => { if (person.age >= 18) adults.push(person); });
console.log(adults.length);

Output:

2

Example 20: Summing Object Properties

const scores = [{ value: 90 }, { value: 85 }];
let total = 0;
scores.forEach(score => total += score.value);
console.log(total);

Output:

175

Advanced Scenarios: Nested Arrays, Functions, and More

Example 21: Flattening Nested Arrays (Partial)

const nested = [[1, 2], [3, 4]];
let flat = [];
nested.forEach(sub => sub.forEach(num => flat.push(num)));
console.log(flat);

Output:

[ 1, 2, 3, 4 ]

Example 22: Calling Functions on Elements

function greet(name) { console.log(`Hi, ${name}!`); }
const friends = ['Ram', 'Sam'];
friends.forEach(greet);

Output:

Hi, Ram!
Hi, Sam!

Example 23: Using Arrow Functions with thisArg

const context = { prefix: 'Item: ' };
[1, 2].forEach(function(num) { console.log(this.prefix + num); }, context);

Output:

Item: 1
Item: 2

Example 24: Handling Empty Array

const empty = [];
empty.forEach(() => console.log('This won\'t run'));
console.log('Empty array done');

Output:

Empty array done

Example 25: Breaking Early

[1, 2, 3].forEach(num => console.log(num));

Output:

1
2
3

Example 26: Asynchronous Simulation

const delays = [100, 200];
delays.forEach(ms => console.log(`Delayed by ${ms}ms`));

Output:

Delayed by 100ms
Delayed by 200ms

Example 27: Modifying Array During Iteration

let arr = [1, 2, 3];
arr.forEach((num, index) => { if (num === 2) arr.splice(index, 1); console.log(num); });
console.log(arr);

Output:

1
2
[ 1, 3 ]

Example 28: Collecting Unique Values

const duplicates = [1, 2, 2, 3];
let unique = new Set();
duplicates.forEach(num => unique.add(num));
console.log([...unique]);

Output:

[ 1, 2, 3 ]

Example 29: Generating HTML List

const listItems = ['Item1', 'Item2'];
let html = '<ul>';
listItems.forEach(item => html += `<li>${item}</li>`);
html += '</ul>';
console.log(html);

Output:

<ul><li>Item1</li><li>Item2</li></ul>

Example 30: Chaining with Other Methods

[1, 2, 3].filter(num => num > 1).forEach(num => console.log(num));

Output:

2
3

Conclusion

The forEach() method is a go-to for straightforward array iteration in JavaScript. While it lacks the return values of methods like map() or the early exit of a for loop, its simplicity shines in scenarios focused on actions per element. Experiment with these examples in your code editor to see them in action, and remember: for mutations or transformations, consider alternatives like map() or reduce().

List of Programs


JavaScript Arrays & Methods Examples


JS Practical Project