Master The Art of Looping in JavaScript With These Incredible TR
Master The Art of Looping in JavaScript With These Incredible TR
by Yogi
via GIPHY
Like the cat, you will also become a Master of JavaScript Looping,
after you know all the looping tricks.
In the same way you can loop through arrays of string too.
I went to the W3Schools site and ran the above code on the browser
console, and see what it did:
Forum Donate
The block of code inside the loop will be executed once for each
property.
a. Looping through an Object Properties
Forum Donate
I have an object that contains some properties. I will use the For In
loop to searchLearn to code
out every — free 3,000-hour
property curriculum
and it’s value.
The below code prints all the properties and their values in the
console window.
jsonData: {
one: [11, 12, 13, 14, 15],
two: [21, 22, 23],
three: [31, 32] Forum Donate
}
The JSON has a root node called ‘jsonData’, and this contains 3 nodes
— ‘one’, ‘two’, ‘three’. The nodes are also called keys.
The below code shows how to extract information from JSON using
the For In loop:
var json = {
jsonData: {
one: [11, 12, 13, 14, 15],
two: [21, 22, 23],
three: [31, 32]
}
};
Explanation: There are 2 For In loops in the above code — Outer loop
& Inner loop.
The Outer Loop runs 3 times and covers nodes ‘one’, ‘two’ & ‘three’.
The Inner Loop covers all the values inside the selected node i.e the
nodes ‘one’, ‘two’, & ‘three’.
Run the code in your web page or in your browser’s console window,
and you will see all the values of the nodes printed, like in the below
image:
Forum Donate
jsonData: [{
one: [11, 12, 13, 14, 15]
}, {
two: [21, 22, 23]
}, {
three: [31, 32]
}]
Now I will use a combination of For & For In loops to extract all
information from this JSON. The below code does this work for me:
var json = {
jsonData: [{
one: [11, 12, 13, 14, 15]
}, {
two: [21, 22, 23]
}, {
three: [31, 32]
}] Forum Donate
};
Learn to code — free 3,000-hour curriculum
for (var i = 0; i < json.jsonData.length; i++) {
for (var key in json.jsonData[i]) {
for (var j = 0; j < json.jsonData[i][key].length; j++) {
console.log(json.jsonData[i][key][j])
}
}
}
You can see that this table does not show the total price of all the
products. So if there is a requirement for you to show the total price
then you can loop through all the prices and show the total in the
Forum Donate
table footer. This is how you will do it.
Learn to code — free 3,000-hour curriculum
Add the HTML Table code to your web page:
<table id="priceTable">
<tr>
<th>Id</th>
<th>Product Name</th>
<th>Product Price</th>
</tr>
<tr>
<td>1</td>
<td>Shirts</td>
<td>49.99</td>
</tr>
<tr>
<td>2</td>
<td>Pants</td>
<td>55.50</td>
</tr>
<tr>
<td>3</td>
<td>Socks</td>
<td>20</td>
</tr>
<tr>
<td>4</td>
<td>Shoes</td>
<td>99</td>
</tr>
<tr>
<td>5</td>
<td>Jackets</td>
<td>88.90</td>
</tr>
</table>
Next, add the CSS for giving proper design to this html table:
<style> Forum Donate
#priceTable {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
Learn to code — free 3,000-hour curriculum
border-collapse: collapse;
width: 100%;
}
#priceTable tr {
background-color: #f2f2f2;
}
#priceTable th {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #4CAF50;
color: white;
}
</style>
Now loop through the table with the While loop and calculate the
sum of all products. So add the below JavaScript code to your web
page that does this work:
var i = 1;
var sum = 0;
while (i < table.rows.length) {
sum += parseFloat(table.rows[i].cells[2].innerHTML)
i++;
}
Explanation: First I get the reference of the table by using var table
= document.getElementById("priceTable") . Then I added 2
variables called ‘i’ and ‘sum’. The variable ‘i’ is the conditional
variable of the while loop, while ‘sum’ will keep adding the price of
every product into it.
So I ran the while loop for the variable ‘i’ value from 1 to the (total
rows -1). I got the total rows in the table by table.rows.length and
added it to the condition of the while loop:
Note: The table has 6 rows from index 0 to 5, and each row has 3
columns from index 0 to 2. I specifically ran the loop from ‘i’ variable
value of 1 and not 0. This is because in the 0th index of the table’s
row there is the column’s name (which I don’t need).
Inside the while loop I kept on adding the values of each product’s
price to the sum variable like this: sum +=
parseFloat(table.rows[i].cells[2].innerHTML) and at the end
increased the value of ‘i’ by 1.
The code which does the addition of this new row is:
The above JavaScript code will create a new row containing the
total price of the product. Now the table will look like:
Forum Donate
b. An infinite Looping
Below is the infinite loop in the While statement:
while (infiVal) {
// your code
}
Note: Infinite loops can hang the browser so it is required to run the
loop at a gap of a few milliseconds. You can use the JavaScript
setInterval method to run a given function every 1000 milliseconds.
See the below code:
function myTimer() {
// your code
}
Reference Tutorial — Understanding “setTimeout()” and
Forum Donate
“setInterval()” timer methods in jQuery/JavaScript
Learn to code — free 3,000-hour curriculum
var i = 2;
do {
alert("Hello");
i++;
}
while (i < 1);
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var cityNames = Array.from(xmlDoc.getElementsByTagName("city"
var i = 0;
do {
console.log(cityNames[i].innerHTML);
i++;
}
while (i < cityNames.length);
}
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
Learn
Then I converted allto code
the city—names
free 3,000-hour curriculum
into an array:
var cityNames =
Array.from(xmlDoc.getElementsByTagName("city"));
Finally I loop through this array of cities using Do While loop and
print each city name in the console window:
var i = 0;
do {
console.log(cityNames[i].innerHTML);
i++;
}
while (i < cityNames.length);
Function1 is the name of the function which gets called for every
element of the array. In my case it will be called 5 times. It accepts 2
parameters — ‘index’ and ‘value’ of the current element.
Conclusion
Thank you for your time reading this tutorial. I hope it has taught
you something new about dealing with loops in JavaScript. Now you
can apply any of your favourite loop tactics, described in this
tutorial, in your web project.
Forum Donate
Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public.
Donations to freeCodeCamp go toward our education initiatives, and help pay for servers,
services, and staff.
Trending Guides
About Alumni Network Open Source Shop Support Sponsors Academic Honesty