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.
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.
array.forEach(callback(currentValue, index, array), thisArg);
If no callback is provided, it throws a TypeError.
const fruits = ['apple', 'banana', 'cherry']; fruits.forEach(fruit => console.log(fruit));
apple banana cherry
const numbers = [10, 20, 30]; numbers.forEach((num, index) => console.log(`Index ${index}: ${num}`));
Index 0: 10 Index 1: 20 Index 2: 30
const colors = ['red', 'green', 'blue']; colors.forEach((color, index, arr) => console.log(`${color} is at position ${index} in [${arr}]`));
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]
const obj = { multiplier: 2 }; [1, 2, 3].forEach(function(num) { console.log(num * this.multiplier); }, obj);
2 4 6
const sparse = [1, , 3]; sparse.forEach(num => console.log(num));
1 3
const nums = [5, 10, 15]; let sum = 0; nums.forEach(num => sum += num); console.log(sum);
30
const values = [8, 3, 11, 5]; let max = -Infinity; values.forEach(val => { if (val > max) max = val; }); console.log(max);
11
const evens = [2, 4, 5, 6, 7]; let count = 0; evens.forEach(num => { if (num % 2 === 0) count++; }); console.log(count);
3
const doubles = [1, 2, 3]; doubles.forEach((num, index, arr) => arr[index] = num * 2); console.log(doubles);
[ 2, 4, 6 ]
const factors = [2, 3, 4]; let product = 1; factors.forEach(factor => product *= factor); console.log(product);
24
const words = ['hello', 'world']; words.forEach((word, index, arr) => arr[index] = word.toUpperCase()); console.log(words);
[ 'HELLO', 'WORLD' ]
const parts = ['Java', 'Script']; let full = ''; parts.forEach(part => full += part); console.log(full);
JavaScript
const sentence = ['a', 'e', 'i', 'o', 'u']; let vowelCount = 0; sentence.forEach(char => { if ('aeiou'.includes(char)) vowelCount++; }); console.log(vowelCount);
5
const strs = ['abc', 'def']; strs.forEach((str, index, arr) => arr[index] = str.split('').reverse().join('')); console.log(strs);
[ 'cba', 'fed' ]
const names = ['Suresh', 'Sam', 'Stanley']; names.forEach(name => console.log(name.length));
6 3 7
const users = [{ name: 'John' }, { name: 'Jane' }]; users.forEach(user => console.log(user.name));
John Jane
const items = [{ price: 10 }, { price: 20 }]; items.forEach(item => item.price += 5); console.log(items);
[ { price: 15 }, { price: 25 } ]
const objArray = [{ a: 1 }, { b: 2 }]; let keys = []; objArray.forEach(obj => keys.push(...Object.keys(obj))); console.log(keys);
[ 'a', 'b' ]
const people = [{ age: 25 }, { age: 17 }, { age: 30 }]; let adults = []; people.forEach(person => { if (person.age >= 18) adults.push(person); }); console.log(adults.length);
2
const scores = [{ value: 90 }, { value: 85 }]; let total = 0; scores.forEach(score => total += score.value); console.log(total);
175
const nested = [[1, 2], [3, 4]]; let flat = []; nested.forEach(sub => sub.forEach(num => flat.push(num))); console.log(flat);
[ 1, 2, 3, 4 ]
function greet(name) { console.log(`Hi, ${name}!`); } const friends = ['Ram', 'Sam']; friends.forEach(greet);
Hi, Ram! Hi, Sam!
const context = { prefix: 'Item: ' }; [1, 2].forEach(function(num) { console.log(this.prefix + num); }, context);
Item: 1 Item: 2
const empty = []; empty.forEach(() => console.log('This won\'t run')); console.log('Empty array done');
Empty array done
[1, 2, 3].forEach(num => console.log(num));
1 2 3
const delays = [100, 200]; delays.forEach(ms => console.log(`Delayed by ${ms}ms`));
Delayed by 100ms Delayed by 200ms
let arr = [1, 2, 3]; arr.forEach((num, index) => { if (num === 2) arr.splice(index, 1); console.log(num); }); console.log(arr);
1 2 [ 1, 3 ]
const duplicates = [1, 2, 2, 3]; let unique = new Set(); duplicates.forEach(num => unique.add(num)); console.log([...unique]);
[ 1, 2, 3 ]
const listItems = ['Item1', 'Item2']; let html = '<ul>'; listItems.forEach(item => html += `<li>${item}</li>`); html += '</ul>'; console.log(html);
<ul><li>Item1</li><li>Item2</li></ul>
[1, 2, 3].filter(num => num > 1).forEach(num => console.log(num));
2 3
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().
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions