More on Loops
This lesson is part of the Web Programming 1 Course.
In the previous lesson you were introduced to loops, and you used them to solve a few problems. You learned about while loops and for loops. And you used them to solve relatively simple problems, such as calculating the sum of an array of numbers (the 'tips' example), and searching for elements in an array (the example in which you searched for an 'A' within an array of letter grades). In this lesson we'll learn about another type of loop (there are actually few more that we won't get to until the next class) and we'll dig deeper into using loops and arrays to solve some very interesting problems.
Looping through the Properties of an Object
You can loop through the property names (aka 'keys') of an object by using a for/in loop.
const dog = {name: "Brutus", breed:"Boxer", gender: "male", age:7, vaccinated:true};
for(let key in dog){
console.log("Key (property name): " + key);
}
There are 3 things that are included inside the parenthesis of this loop:
- Declare a variable named key (although you could use any variable name you like) which can be used inside the body of the loop where it will store the 'current' property name (key).
- After declaring the variable, use the in keyword.
- After the in keyword, add the name of the variable that is storing the object.
When you run this code, you'll see the following in the log: name, breed, gender, age, vaccinated.
Often times you'll want to work with the property values (not just the keys) inside the body of the loop. To do this, you could modify the previous example to look like this:
for(let key in dog){
console.log("Key: " + key);
console.log("Value: " + dog[key]);
}
The key to understanding this (no pun intended) is the use of bracket notation to access the value of the property: dog[key]. The key variable is storing the 'current' property name. In the first iteration of the loop, the key variable evaluates to the string 'name'. So, the expression dog[key] becomes dog['name']. You wouldn't be able to accomplish this by using dot notation. This may raise some questions about the difference between dot and bracket notation when working with objects. If you are interested in discussing it further, please ask me during class.
Strings are Arrays
Strings are actually a type of array, and each character is an element that has an index number. Just like other arrays, you can use bracket notation and an index number to access each element. Strings have a length property that stores the number of characters in the string. Here's a code sample that loops through the characters in a string:
const str = "Hello world!";
console.log("Number of characters in the string: " + str.length);
for(let i = 0; i < str.length; i++){
const currentCharacter = str[i];
console.log(currentCharacter + " is at index " + i);
}
Calculating Min, Max and Averages
Let's revisit the 'dailyTips' array that we worked with in the last lesson. We have already seen how to calculate the total of all the numbers in the array. After figuring out the total, it becomes easy to calculate the average by making use of the length property:
const dailyTips = [40, 80, 107, 92, 77];
let totalTips = 0;
for(let x = 0; x < dailyTips.length; x++){
totalTips += dailyTips[x];
}
console.log("The total is: " + totalTips);
const avg = totalTips/dailyTips.length;
console.log("The average is: " + avg);
You can write code that figures out the highest number in the array like so:
let max = 0;
for(let x = 0; x < dailyTips.length; x++){
const current = dailyTips[x];
if(current > max){
max = current;
}
}
console.log("The max is: " + max);
In this sample, the max variable is declared and initialized to 0. Then, inside the body of the loop we check to see if the current element is greater than the max. If so, then we replace the value of max with the current element. This is a good sample to step through with the debugger, and watch the max variable as the loop iterates.
To calculate the minimum value, we'll take a slightly different approach:
let min = dailyTips[0]; // initialize min to the value of the first element in the array
// start the loop at the second element (at index 1):
for(let x = 1; x < dailyTips.length; x++){
const current = dailyTips[x];
if(current < min){
min = current;
}
}
console.log("The min is: " + min);
Working with Arrays of Objects
As a web developer, you will often find yourself working with arrays of objects. For the next few code samples, we'll be working with the dogs array that we used in the previous lesson:
const dogs = [
{name: "Brutus", breed:"Boxer", gender: "male", age:7, vaccinated:true},
{name: "Fido", breed:"Pit Bull", gender: "female", age:3, vaccinated:false},
{name: "Daisy", breed:"Labrador", gender: "female", age:2, vaccinated:true}
];
This array is very small, only 3 elements, which will keep thins nice and simple for us. But a real-world program could work with extremely large arrays that have thousands, millions, or even billions of elements.
Searching for Elements in an Array of Objects
It's very common for a program to allow users to search through a large data set, such as an array of objects. In this example we'll prompt the user to enter the name of a dog, and then we'll use a loop to search for that dog:
const input = prompt("Enter the name of a dog.");
for(let x = 0; x < dogs.length; x++){
const d = dogs[x]; // store the 'current' dog in the d variable
if(d.name == input){
console.log(d.name + " is at index " + x);
console.log(d);
break;
}
}
Data Analytics with Loops and Arrays
You can find all sorts of interesting information by looping through an array of objects. For example, if you needed to figure out the number of dogs that have been vaccinated, you could do it like so:
let numberOfVaxedDogs = 0;
for(let x = 0; x < dogs.length; x++){
if(dogs[x].vaccinated){
numberOfVaxedDogs++;
}
}
console.log("Number of vaccinated dogs: " + numberOfVaxedDogs);
Here are some other interesting problems that we can solve together in class:
- The average age of all the dogs
- How many male dogs have been vaccinated.
- How many dogs under the age of 5 have been vaccinated