The forEach method is used to iterate over elements in an array and execute a provided function once for each array element. Here are a few examples:
Example 1: Basic Usage
const numbers = [1, 2, 3, 4, 5];
// Using forEach to log each element in the array
numbers.forEach(function(number) {
console.log(number);
});
Example 2: Doubling the Elements
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = [];
// Using forEach to double each element in the array
numbers.forEach(function(number) {
doubledNumbers.push(number * 2);
});
console.log(doubledNumbers);
Example 3: Modifying the Original Array
const fruits = ['apple', 'banana', 'orange'];
// Using forEach to capitalize each fruit in the array
fruits.forEach(function(fruit, index, array) {
array[index] = fruit.toUpperCase();
});
console.log(fruits);
Example 4: Using Arrow Function
const colors = ['red', 'green', 'blue'];
// Using forEach with an arrow function to log each color
colors.forEach(color => console.log(color));
Example 5: Iterating over an Object (not recommended)
While forEach is primarily designed for arrays, you can also use it with objects in certain scenarios. However, it’s generally not recommended, and other methods like Object.keys or Object.entries are more suitable for iterating over object properties.
const person = { name: 'John', age: 30, job: 'developer' };
// Using forEach to log each property of the person object
Object.keys(person).forEach(key => {
console.log(`${key}: ${person[key]}`);
});