Javascript forEach() method: examples, index, map, break continue return
When you need to use arrays and loops in JavaScript. One of the most commonly used methods is the forEach()
method.
In this article, we'll look at examples of using the forEach()
method, the index
and array
parameters,
how it differs from other methods like map()
, and how to use the break
continue
return
keywords.
The forEach()
method is implemented not only for arrays, but also for most JavaScript data types such as sets and maps.
We'll only look at the array method this time.
To run Node.js, I recommend installing with asdf. You can read more about that in this post.
1. JavaScript forEach() Basics
1.1. Understanding the Array.prototype.forEach() method
The forEach
method is part of the Array.prototype
object, so it is available to all array instances.
This method provides a readable way to traverse an array and perform a specified function on each element.
The forEach()
method takes a callback function as a parameter, which it executes for each element in the array.
1.2. forEach() method basic syntax
The basic syntax for using the forEach()
method is simple.
array.forEach(function callback(currentValue[, index[, array]]) {
// Your code here
})
The callback function takes three parameters: the current value, the index, and the array.
The currentValue
represents the current element in the array, the index
represents its position, and the array
is a reference to the array itself,
The parameters index
and array
are optional.
Here's an example using the simple forEach()
method.
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(number => console.log(number));
1.3. Compared to the regular for statement
Compared to the traditional for
statement, the forEach()
method provides a more readable and concise syntax.
It also prevents developer errors such as out-of-index iterations or array values being modified, causing errors.
However, forEach should be used with the caveat that it does not provide the same level of control as the for
statement, especially when breaking out of iterations or skipping iterations.
2. forEach(), map() differences
Other methods available for iterating over arrays in JavaScript include filter(), map(), and reduce().
These methods are more specialized than forEach
and are optimized for specific use cases:
map()
: converts an array by applying a callback function to each element and returns a new array with the converted elements.Reduce()
: reduces the values in an array to a single value by applying a function that combines the previous value with the current value.filter()
: Creates a new array, keeping only those elements that meet a specified condition.
Note that the map()
method returns a new array, while the forEach()
method always returns undefined
.
For more information about the other array methods, please see their respective articles.
3. break, continue, return keywords in the forEach() method
The basic premise of the functional programming-based forEach()
method is to traverse all elements of the array.
As a result, it does not support the use of the break
and continue
keywords to pause or resume traversal.
However, you can use the return
keyword to take over the role of the break
keyword.
In the example below, when the element value is 3
, you can see that the return
keyword is used to break to the next element.
const array = [1, 2, 3, 4, 5];
array.forEach((element) => {
if (element === 3) {
return; // Skips the current iteration
}
console.log(element);
});
4. Examples of using forEach()
4.1. Cleaning and formatting data
The JavaScript forEach()
method can be useful for cleaning and formatting data before processing or displaying it.
For example, let's say you have an array of user objects with mixed case names.
You can use the forEach()
method to standardize the case:
const users = [
{ id: 1, name: "ALICE" },
{ id: 2, name: "BOb" },
{ id: 3, name: "Charlie" }
];
users.forEach((user) => {
user.name =
user.name.charAt(0).toUpperCase() + user.name.slice(1).toLowerCase();
});
console.log(users);
// Output:
// [
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Bob' },
// { id: 3, name: 'Charlie' }
// ]
In this example, the forEach()
method iterates over the users
array, changing each user's name to the appropriate capitalization.
This type of data organization helps ensure consistency throughout the application, making the data easier to view and manipulate.
4.2. Manipulating the DOM
The forEach()
method makes it easy to iterate over HTMLCCollections to manipulate DOM elements.
For example, you might want to add a class to all elements with a particular class name:
const elements = document.getElementsByClassName("target");
Array.prototype.forEach.call(elements, (element) => {
element.classList.add("new-class");
});
It can also be used to change the properties or content of DOM elements.
For example, if you wanted to change the src
attribute of all image
elements with a certain class name, you could do something like this
const images = document.querySelectorAll(".image-class");
images.forEach((image) => {
image.src = "new-image-source.jpg";
});
4.3. Chaining forEach with other array methods
You can concatenate the forEach()
method with other array methods to create more powerful and readable code.
For example, let's say you have an array of orders and you want to calculate the total revenue for orders of a particular product:
const orders = [
{ id: 1, product: "A", price: 10, quantity: 2 },
{ id: 2, product: "B", price: 20, quantity: 1 },
{ id: 3, product: "A", price: 10, quantity: 3 },
{ id: 4, product: "C", price: 30, quantity: 1 }
];
const targetProduct = "A";
const totalRevenue = orders
.filter((order) => order.product === targetProduct)
.map((order) => order.price * order.quantity)
.reduce((acc, curr) => acc + curr, 0);
console.log(totalRevenue);
In this example, we first filter the array of orders to keep only those orders that contain the target product.
Then it uses the map
method to calculate the revenue of each filtered order.
Finally, it accumulates the total revenue using the reduce
method.
This chaining approach results in more readable and functional code, which makes the code easier to understand and maintain.
5. Using index, array parameters within callback functions
The callback function of the forEach()
method provides references to access not only the current value, but also each index and the array itself.
This allows you to define a more flexible callback function.
const numbers = [10, 20, 30, 40, 50];
numbers.forEach((number, index, array) => {
console.log(`Index: ${index}, Number: ${number}, Array: ${array}`);
});
// Output:
// Index: 0, Number: 10, Array: 10,20,30,40,50
// Index: 1, Number: 20, Array: 10,20,30,40,50
// Index: 2, Number: 30, Array: 10,20,30,40,50
// Index: 3, Number: 40, Array: 10,20,30,40,50
// Index: 4, Number: 50, Array: 10,20,30,40,50
6. Implementing a Custom forEach Method
In some cases, you may want to extend the functionality of forEach to suit your needs.
For example, you may want to create a custom forEach function to quickly exit the loop, such as a break
statement from a for
statement, or to provide additional parameters to a callback function.
To create a custom forEach function, you can use a for
statement and pass any parameters you want.
Here's an example of a custom forEach function with a break
function:
function customForEach(array, callback) {
for (let i = 0; i < array.length; i++) {
const result = callback(array[i], i, array);
if (result === false)
break;
}
}
const numbers = [1, 2, 3, 4, 5];
customForEach(numbers, (number) => {
if (number > 3) return false; // "break" when number > 3
console.log(number);
});
// Output:
// 1
// 2
// 3
7. Conclusion
In this article, we've covered an example of using the forEach()
method, how it differs from other methods such as index
, array
parameters, map()
,
using the break
, continue
, return
keywords, and more.
By understanding the strengths and limitations of the forEach()
method, which allows you to write cleaner and more efficient code, you'll be better equipped to tackle a variety of web development challenges.
I encourage you to continue exploring forEach()
and other array methods to improve your JavaScript skills and create more effective and engaging web applications.
