Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
The forEach()
method is a fundamental array method in JavaScript that allows you to iterate over the elements of an array and apply a provided callback function to each element. It is often used for performing operations on array elements, such as logging, transformation, or manipulation.
Here's a deep dive into the forEach()
method:
javascriptarray.forEach(callback(currentValue, index, array));
array: The array you want to iterate over.
callback: A function that is called for each element in the array. It can take up to three parameters:
currentValue: The current element being processed in the array.
index (optional): The index of the current element being processed.
array (optional): The array forEach()
was called upon.
Let's use forEach()
to log each element of an array to the console:
javascriptconst fruits = ['apple', 'banana', 'cherry'];
fruits.forEach(function (fruit) {
console.log(fruit);
});
In this example, the forEach()
method iterates through the fruits array and applies the provided callback function to each element, logging each fruit to the console.
The forEach()
method does not return a value. It is designed for performing side effects, such as modifying global variables, logging to the console, or updating elements outside of the array.
While forEach()
doesn't return a new array, you can use it to modify the original array by directly accessing and updating elements within the callback function:
javascriptconst numbers = [1, 2, 3];
numbers.forEach(function (number, index, array) {
array[index] = number * 2;
});
console.log(numbers); // Outputs: [2, 4, 6]
In this example, the forEach()
loop is used to double the value of each element in the numbers array in-place.
The forEach()
method is typically used when you want to perform an operation on each element in the array without the need to create a new array.
The callback function in forEach()
is executed for each element in the order they appear in the array.
forEach()
is a good choice when you want to apply a function to each element and don't need the returned values to create a new array.
If you need to return a new array with transformed elements, you might consider using methods like map()
.
Here's an example of using forEach()
to filter elements within an array and create a new array:
javascriptconst numbers = [1, 2, 3, 4, 5];
const evenNumbers = [];
numbers.forEach(function (number) {
if (number % 2 === 0) {
evenNumbers.push(number);
}
});
console.log(evenNumbers); // Outputs: [2, 4]
In this example, we use forEach()
to filter even numbers and store them in a new array, evenNumbers.