+ 1

forEach() method

How does the forEach() method index the elements in an array? For instance if I have an array and I want to iterate over it and show the index of each array item I can do it with a for() method loop like this: var fruits = ["Apples", "Bananas", "Cherries"]; //using for loop to iterate over the fruits array and showing their index value. for(var i = 0; i < fruits.length; i++) { document.write(i + ": " + fruits[i] + "<br>"); } OUTPUT: 0: Apples 1: Bananas 2: Cherries //I can also do this using the forEach() method like this: fruits.forEach(function(fruitsItem, index, fruits) { document.write(index + ": " + fruitsItem + "<br>"); }); This will give same output but in the for() method I had to initialize the i variable with 0 to give the desired output but I don't need to the same with the forEach() method. How does this works?

9th Oct 2020, 12:44 PM
Logos - avatar
2 Answers
+ 2
You ask about the index but it sounds like you basically want a deeper understanding of how forEach is implemented. Here is some code that basically reimplements the standard forEach but under the name 'myForEach'. I hope this implementation reveals how the index and other parameters are passed in. Check out this: function myForEach(a, callback) { for (var i = 0; i < a.length; i++) { callback(a[i], i, a); } } var fruits = ["Apples", "Bananas", "Cherries"]; myForEach(fruits, function(fruitsItem, index, fruits) { document.write(index + ": " + fruitsItem + "<br>"); }); Let's add that as part of the Array prototype to make it callable in an even more similar way. Array.prototype.myForEach = function(callback) { for (var i = 0; i < this.length; i++) { callback(this[i], i, this); } } var fruits = ["Apples", "Bananas", "Cherries"]; fruits.myForEach(function(fruitsItem, index, fruits) { document.write(index + ": " + fruitsItem + "<br>"); }); One part of this question I don't understand is where you say, "I don't need to the same with the forEach() method." What are you trying to change?
9th Oct 2020, 6:39 PM
Josh Greig
Josh Greig - avatar
What I meant was that I don't need to manually index the array items in the forEach() method unlike the for() method where I need to say var i = 0 as a parameter. Thank you, this was very helpful, now I have an understanding of how the forEach method works. There is a function inside a loop in the forEach() method that automates the parameters passed to it.
11th Oct 2020, 11:53 AM
Logos - avatar