One of the most widely used utility functions for array traversal in JavaScript is the forEach() method. Here is a quick rundown of how the function works, its syntax, use cases, and some important things to keep in mind:
π Download eBook - JavaScript: from ES2015 to ES2023
.
Overview
The forEach() method runs a provided function once for each element in an array. This is quite cleaner and far more readable compared to the traditional for-loops for traversal across arrays.
Syntax
array.forEach(function(currentValue, index, array) {
// code to execute for each element
}, thisArg);
-
function(currentValue, index, array): A function to run on each element in this array. It takes three arguments:-
currentValue: The current element being processed. -
index(optional): The index of the current element being processed. -
arrayoptional: The arrayforEachwas called upon
-
-
thisArgoptional: Value to use asthiswhen executing the callback function.
Example Usage
Here are some examples to showcase the use of forEach():
Basic Example
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
This will output:
1
2
3
4
5
Using Index and Array Parameters
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number, index, array) {
console.log('Index:', index, 'Value:', number);
console.log(array);
});
This will output each index and value pair, and print the entire array for each iteration.
Arrow Function
Using an arrow function makes the code more concise:
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number));
Practical Use Cases
-
Logging Each Element:
forEachis often used to perform an action for every item in an array, such as logging to the console or modifying DOM elements. -
Summing Values: Although
reduce()is typically used for summing values,forEachcan also be used to accumulate a sum. - Updating Elements: Apply a transformation or operation on each element of an array.
Important Details
-
No Return Value:
forEachalways returnsundefined, so it should not be used if you need to derive a new array based on the original. Usemap()instead in such cases. -
Does Not Mutate the Array: Although
forEachitself does not mutate the array, the function you provide can modify the elements of the array. -
Break or Continue: You cannot break out of a
forEachloop. If you need such control flow, consider using a traditionalforloop orArray.prototype.every()orArray.prototype.some().
Comparison with Other Iteration Methods
-
forLoop: More verbose but offers complete control over iteration, including the ability to break out of the loop. -
map(): Creates a new array with the results of calling a function on every element, whileforEachdoes not return a new array. -
filter(): Creates a new array with all elements that pass a test implemented by the provided function. -
reduce(): Executes a reducer function on each element of the array, resulting in a single output value.
Conclusion
The forEach() method is a simple yet powerful way to iterate over arrays in JavaScript, making code cleaner and easier to read. It is ideal for cases where you want to execute a function on each element of an array without the need to return a new array or break out of the loop. However, if you need more control or different behaviour, consider other iteration methods such as for loops, map(), or reduce().
π Download eBook
Top comments (2)
Good work