Get your team started on a custom learning journey today!
Our Boulder, CO-based learning experts are ready to help!
Get your team started on a custom learning journey today!
Our Boulder, CO-based learning experts are ready to help!
Follow us on LinkedIn for our latest data and tips!
This tutorial demonstrates using the Array.forEach() method to loop through arrays with some examples.
forEach() is designed to run a function on each indexed element in an array. Starting at index[0] a function will get called on index[0], index[1], index[2], etc… forEach() will let you loop through an array in much the same way as a for loop.
Let’s take a look at some parameters passed into the forEach() callback function. These parameters include the current value, array index, and also the array itself.
Array.forEach( function(current_value, index, initial_array) {}, this_context )
These parameters helpful when traversing an array to perform some task on each array index value.
this_context is an optional parameter to set scope, and a more in depth explanation can be found at the following Array.prototype.forEach() MDN article
forEach is great for looping over an array of values to run a function on each value. Also, forEach() is a good alternative to using a for() loop. forEach let’s us reuse a callback function for readability. The below example compares the readability of a for loop versus using the forEach() method.
var my_array = ['a', 'b', 'c']; for (var i=0; i<my_array.length; i++) { console.log(my_array[i]); //a b c } my_array.forEach(function(current_value) { console.log(current_value); //a b c });
Let’s start with an example using forEach() to loop through an array of numbers. This example checks if each number in the javascript array is even or odd.
var array_of_numbers = [5, 7, 1, 9, 8, 5]; array_of_numbers.forEach(function(current_value, index, initial_array) { if (current_value % 2) { console.log('odd'); } else { console.log('even'); } }); //odd, odd, odd, odd, even, odd
The following example uses the forEach() array method to separate even numbers from odd numbers into two separate arrays.
var even_numbers = []; var odd_numbers = []; function separate_evens_from_odds(value) { if ( value % 2 ) { odd_numbers.push(value); } else { even_numbers.push(value); } } var array_of_numbers = [5, 7, 1, 9, 8, 5]; array_of_numbers.forEach(separate_evens_from_odds); console.log(even_numbers); //[8] console.log(odd_numbers); //[5, 7, 1, 9, 5] //
What if we had a couple of shopping carts of items? Say you wanted to total the cost of your shopping cart. The following example totals the cost of all items from our shopping carts using the forEach() method.
var total_cost = 0; function add_to_total_cost(amount) { total_cost += amount.cost; } var shopping_cart_1 = [ { item: 'shirt', cost: 22 }, { item: 'shorts', cost: 26 } ]; var shopping_cart_2 = [ { item: 'cereal', cost: 4 }, { item: 'milk', cost: 3 }, { item: 'eggs', cost: 2 } ] shopping_cart_1.forEach(add_to_total_cost); shopping_cart_2.forEach(add_to_total_cost); console.log(total_cost); //57
For more examples of looping through or iterating over javascript arrays or objects checkout this 2ality post on Iterating over arrays and objects.
While the forEach() method can be useful, forEach() does come with some disadvantages. Maybe you are wondering how to break out of a forEach() loop early. One of the negative issues with using forEach() is that there is no way to terminate or break out of the loop without throwing an exception. Since a forEach() returns a value of undefined, forEach() is not chainable like map(), filter(), or reduce().
forEach is great for looping through an array to execute a function on each of those values. forEach() is also a nice alternative to using a for() loop for code reuse and readability.
Customized Technical Learning Solutions to Help Attract and Retain Talented Developers
Let DI help you design solutions to onboard, upskill or reskill your software development organization. Fully customized. 100% guaranteed.
DevelopIntelligence leads technical and software development learning programs for Fortune 500 companies. We provide learning solutions for hundreds of thousands of engineers for over 250 global brands.
“I appreciated the instructor’s technique of writing live code examples rather than using fixed slide decks to present the material.”
VMwareDevelopIntelligence has been in the technical/software development learning and training industry for nearly 20 years. We’ve provided learning solutions to more than 48,000 engineers, across 220 organizations worldwide.
Thank you for everyone who joined us this past year to hear about our proven methods of attracting and retaining tech talent.
© 2013 - 2022 DevelopIntelligence LLC - Privacy Policy
Let's review your current tech training programs and we'll help you baseline your success against some of our big industry partners. In this 30-minute meeting, we'll share our data/insights on what's working and what's not.
Training Journal sat down with our CEO for his thoughts on what’s working, and what’s not working.