Introduction
JavaScript introduced its 6th edition in June 2015. The 6th edition of JavaScript is popularly known as ES6 or ECMAScript. ES6 gave JavaScript some of the new, modern and powerful methods, and one such method is .forEach(). This method is used to loop through all the elements of an array and at the same time execute a provided function for every array’s element.
Earlier developers (including me) were using the jQuery Each method - .each(), for doing the process of looping over the array elements. But now all these works can be simply done by the JavaScript’s .forEach() method. So I present you with the 7 ways to avoid jQuery Each method with an equivalent JavaScript .forEach() method on your website.
Syntax of JavaScript .forEach()
The syntax is fairly simple:
array.forEach(function(currentValue, index, arr), thisValue)
The 1st parameter is a ‘Required’ one and is a callback function that runs for each element of the array. This callback function has 3 parameters - function (currentValue, index, arr)
- currentValue – ‘Required’, specifies the value of the current element.
- index – ‘Optional’, specifies the index of the current element in the array
- arr – ‘Optional’, specifies the array object the current element belongs to.
The this value is the 2nd parameter of the .forEach() method. It is an ‘Optional’ parameter which specifies a value to be passed to the function to be used as its "this" value. If this parameter is empty, the value "undefined" will be passed as its "this" value. This parameter is hardly used in the .forEach() method so simply avoid it all the time.
Now let us start with the 7 way of using the .forEach() method.
First way – Looping through an Array
You can loop through all the elements of an array with the .forEach() method. In the below code I am showing the index and value of each element of the array in the console.
var names = ["yogi", "alia", "john", "cindy", "david"];
names.forEach(myFunction);
function myFunction(currentValue, index) {
console.log("Array Current Index is: " + index + " :: Value is: " + currentValue);
}
On executing this code you will get the following output on the console,
Second way – Looping through DOM elements
Here I will get all the anchors given in a web page. I will then loop through all of these anchors and show their contents.
var links = document.getElementsByTagName("a");
var linksArr = Array.from(links);
linksArr.forEach(myFunction);
function myFunction(currentValue) {
console.log(currentValue);
}
I first get these anchors by using the getElementsByTagName() function and then converting its result to an array by using the Array.from() method.
Run the above code in the console of any web page and you will see the result as shown below,
If you want to do the same thing with the jQuery Each method then the code will be:
$("a").each(function(index,value) {
console.log($(this).attr("href"));
});
Third way – Extracting values from JSON
Suppose you have a JSON which contains the City names. I want to extract all the city names from it. In that case I can use JavaScript .forEach() code like this:
var json = [{ "City": "Washington DC" }, { "City": "Islamabad" }, { "City": "Beijing" }, { "City": "Tokyo" }];
json.forEach(function (currentValue, index) {
console.log(currentValue.City)
});
The output produced in this case is shown below,
Fourth way – Extracting values from XML
You can also extract values from an XML using the .forEach() method. Check the below code:
var xml = "<cities><city>Washington DC</city><city>Islamabad</city><city>Beijing</city><city>Tokyo</city></cities>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(xml, "text/xml");
Array.from(xmlDoc.getElementsByTagName("city")).forEach(function (currentValue, index, arr) {
console.log(currentValue.textContent)
});
Explanation
Here the variable called ‘xml’ contains the XML. I first parsed the text string contained in ‘xml’ variable into an XML DOM object, which is done by the below 2 lines:
parser = new DOMParser();
xmlDoc = parser.parseFromString(xml, "text/xml");
Next, I fetched all anchors from this XML DOM object (which is ‘xmlDoc’) and converted it into an array:
Array.from(xmlDoc.getElementsByTagName("city"))
Finally I looped through this array using the .forEach() method and extracted the city name from it.
Fifth way – Looping through DOM elements with a certain CSS class
In this example I get all the elements having “w3-example” class by using the getElementsByClassName() method. I then converted it to an array and used .forEach() for looping through all the elements in the array. See the below code.
var elements = document.getElementsByClassName("w3-example");
var elementsArr = Array.from(elements);
elementsArr.forEach(myFunction);
function myFunction(currentValue, index) {
console.log(currentValue);
}
I ran the above code in the console window of w3schools site and got 4 elements having the w3-example class. Check the below image:
Sixth way – Animations with JavaScript .forEach()
It may feel impossible to do animations with the .forEach() method but there is a way. Let me show you.
Here I will make 3 divs to expand and collapse, in a widthwise direction, by showing a good animation effect.
I have 3 div elements with CSS class called ‘block’, and each having a width of 75pixels.
<div class="animateDiv">
<div class="block" style="width:75px"></div>
<div class="block" style="width:75px"></div>
<div class="block" style="width:75px"></div>
</div>
<button onclick="CallForEach()">Click</button>
There is also a button on whose click event I will change the width of these 3 divs to 0 pixels with animation effect.
First add 2 CSS classes in your page head.
<style>
.animateDiv {
display: inline-block;
width: 100%;
padding: 50px;
background: #000;
}
.block {
height: 75px;
border: solid 1px #FFF;
float: left;
margin-right: 25px;
transition: all .3s ease-in-out;
}
</style>
Notice the transition property transition - all .3s ease-in-ot; which tells that whenever any property of the .block class changes then the change will be done with ease-in-out effect in 3 seconds time.
function CallForEach() {
var elements = document.querySelectorAll(".block");
elements.forEach((a, b) => {
setTimeout(function () {
if (a.style.width == "75px")
a.style.width = "0px";
else
a.style.width = "75px";
}, b * 2000);
});
}
Now add the CallForEach() function which will be called in the button click event.
Explanation
Let me explain what this function does. First it gets all the elements having the .block CSS class which in my case is the 3 divs. I do this by using JavaScript’s querySelectorAll() method, and this method gives all these elements in an array form.
Next, I loop through the elements array (that contains the 3 divs) by using the .forEach() method like this:
elements.forEach((a, b) => {
//…
});
I used the lambda expression to define my callback function. The lambda expression contains 2 parameters (a,b), which are for the currentValue and Index of the current element of the array.
Now inside the .forEach() method I am using the .setTimout() function of JavaScript.
Reference- JavaScript setTimout() Method
setTimeout(function () {
if (a.style.width == "75px")
a.style.width = "0px";
else
a.style.width = "75px";
}, b * 2000);
I do a very interesting thing, by delaying the execution of the codes inside the .setTimout() function to run at a delay of 2 seconds time. I do this by providing a value of b*2000 for the time delay parameter. Remember b is the index of the current element of the array.
So that means the codes inside the .setTimeout() function will run at,
- 0 seconds for the first element since 0*2000=0 second.
- 2 seconds for the first element since 1*2000=2 seconds.
- 4 seconds for the first element since 2*2000=4 seconds.
And what I do inside the .setTimout() function is.
if (a.style.width == "75px")
a.style.width = "0px";
else
a.style.width = "75px";
I am checking if the width of the div is 75px so in that case simply make it to 0px. Else if the width of the div is not 75px i.e 0px, then make it to 75pixels. So with these codes, the 3 divs will expand and collapse, in widthwise direction with a good animation effect.
Run these codes on your web page and click the button. You will see the 3 divs collapse one by one. Now click the button once more and this time the 3 divs expand one by one with animations.
See this animation in the below video,
Seventh way – Multiplying by JavaScript .forEach()
In this last way to use the .forEach() method, I will find out the multiplication of all the number of an array. See the below code:
var total = 1;
var numbers = [1, 2, 3, 4, 5];
numbers.forEach(myFunction);
function myFunction(currentValue, index) {
total *= currentValue;
}
console.log(total);
I defined a variable called total with a value of 1. In this variable, the multiplication of all the numbers will be kept.
Inside the .forEach() method I have - total *= currentValue; and that gives me the multiplication of all the elements of the array.
When you run this code you will get a value of 120 in the console window.
Conclusion
The JavaScript .forEach() method is such a valuable method and you can use it to make your code much shorter and smarter. I hoped you enjoyed learning these 7 ways of using this powerful method.
Check my other C# Corner articles:
Do let me know about it in the below comments section. Thank you!