Table of contents
Hey guys, today’s article will be a quick one and it’s about one of the most common array methods which is the forEach
method. let’s dive right into it 😀
What is forEach
method?
The forEach()
method executes a provided function once for each array element. (Mdn docs).
Basically, the forEach()
method is one of the better ways to loop through arrays rather than using a for()
loop. Unlike the other array methods, it does not return anything to you.
Syntax
Let’s see the syntax of the forEach
method before we see an example.
forEach(function (element, index, array) { /* … */ })
From the code above, the forEach
method takes in a callback
function that also takes in three different parameters which are:
element
- The element you are iterating.
index
- The current index of each element.
array
- The array to which the elements belong to.
💡 The element
is the most important and required parameter, the other two are optional.
How it Works
Let’s see an example of how the forEach
method works 👇🏽
const fruits = ['Apple', 'Orange', 'Grape', 'Mango', 'Banana'];
fruits.forEach((fruit) => console.log(fruit));
//output:
//Apple
//Orange
//Grape
//Mango
//Banana
From the example above, we created an array of fruits
. And to get each individual fruit using the forEach
method, We did some things which are;
Got the entire array (which is the
fruits
array).Added the
forEach
method.Got each fruit from the array.
Console logged them out.
Conclusion
Congrats on getting to the end of the article, 🎉. Hope you learned something from this article. See you next week and have a great weekend 😀