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. -
array
optional: The arrayforEach
was called upon
-
-
thisArg
optional: Value to use asthis
when 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:
forEach
is 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,forEach
can 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:
forEach
always 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
forEach
itself 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
forEach
loop. If you need such control flow, consider using a traditionalfor
loop orArray.prototype.every()
orArray.prototype.some()
.
Comparison with Other Iteration Methods
-
for
Loop: 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, whileforEach
does 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()
.
Top comments (2)
Good work