People Example: Loops
This is a example of a looping function:
While it is complex at first, this for loop has three basic parts:
- Keep an array of people, all within one variable.
- Arrays have multiple pieces of information (in this case a name, age, and email address).
- Create a table to list the people within.
- Fill each person's information into the table, until there are no more people left.
Now, let's talk through how to do this.
Arrays
First, you need an array of people. For this example, I'll give you mine to copy:
var users = [
{ name: "John Wick", age: 25, email: "john@example.com" },
{ name: "Alice (In) Wonderland", age: 30, email: "alice@example.com" },
{ name: "Bob Ross", age: 28, email: "bob@example.com" },
{ name: "Emily", age: 22, email: "emily@example.com" },
{ name: "Michael Myers", age: 35, email: "michael@example.com" },
{ name: "Samantha", age: 29, email: "samantha@example.com" },
];
Table
Now that you have your users, how will you list them?
You'll need a table for that!
Normally, table code looks like this:
<table>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</table>
That creates this table:
| Header 1 | Header 2 |
|---|---|
| Row 1, Cell 1 | Row 1, Cell 2 |
| Row 2, Cell 1 | Row 2, Cell 2 |
NOTE: My tables are styled, so yours might look a little different.
Adding User information
Our table is going to be a little less straightforward.
Because we are adding information to the table with a loop, we need to do something called appending to our table.
This code is pretty advanced, so I'll provide all the hard parts for you. I'll try and break down the parts as we add them, though.
Let's start by creating our table, like so:
var userTable = document.getElementById("userTable");
var table = document.createElement("table");
This code does the following:
- Creates a variable that looks for a section on the page with the ID of "userTable"
- Creates an empty table element in a variable called "table".
This should go before the start of the for loop, because we will be calling these variables in the loop.
Alright, here is where the actual loop comes into play. For this, we will want a for loop, as it fits the criteria best.
If you remember, the code for a for loop is as follows:
for(i = 0; [stopper]; i++) {
//Insert code to be repeated
}
In this case, the stopper attribute should be when i is greater than the count of people in the table.
This can be achieved by using users.length. (remember, "users" is the name of our array of people)
Now, your code should look like this:
for (var i = 0; i < users.length; i++) {
//Insert code to be repeated
}
Next, we need to get each indidvidual user, so we can add them to the table.
For this, we're going back to our favorite letter: i. The variable "i" works as an index, because it increases during every "run" of the loop.
So, using i to seperate our users, we get the following code:
var userTable = document.getElementById("userTable");
table = document.createElement("table");
for (var i = 0; i < users.length; i++) {
var user = users[i];
}
Now, we need to add a row for our user to be put in. Once again we will be using code you haven't learned yet, but hopefully you'll start to see a pattern.
var userTable = document.getElementById("userTable");
table = document.createElement("table");
for (var i = 0; i < users.length; i++) {
var user = users[i];
var row = document.createElement("tr");
}
Just like when we created the table earlier, we used document.createElement to add a new element to our website.
We're almost done! Now we need to add the indidvidual cells to the table, known as <td> elements.
I'm only going through the process of adding one element in depth, as the process is the same for all the elements each user has.
For this example, I'll show how to add the user's name to the table. First, let's create the <td> element:
var userTable = document.getElementById("userTable");
table = document.createElement("table");
for (var i = 0; i < users.length; i++) {
var user = users[i];
var row = document.createElement("tr");
var userName = document.createElement("td");
}
This code will create a new cell in the user's row, and call it "userName".
Next, we need to add the content to this cell. We can call the name of this specific user by using our user variable from earlier:
var userTable = document.getElementById("userTable");
table = document.createElement("table");
for (var i = 0; i < users.length; i++) {
var user = users[i];
var row = document.createElement("tr");
var userName = document.createElement("td");
userName.textContent = user.name;
}
This sets the data in the "userName" cell of the row to the name of the user (which we found by using user.name).
Now, once you've done this same process for all the other cells of user infomation, your code will look something like this:
var userTable = document.getElementById("userTable");
table = document.createElement("table");
for (var i = 0; i < users.length; i++) {
var user = users[i];
var row = document.createElement("tr");
var index = document.createElement("td");
index.textContent = i + 1;
var userName = document.createElement("td");
userName.textContent = user.name;
var userAge = document.createElement("td");
userAge.textContent = user.age;
var userEmail = document.createElement("td");
userEmail.textContent = user.email;
}
This will create cells for ID, Name, Age, and Email for a user, and fill it with their information.
NOTE: The ID of a user is increased by one because i (which we use to determine ID) has a default of 0.
Alright, two more steps! Now, we need to append the data into the table rows.
We do this by using .appendChild statments, like this:
row.appendChild(index);
row.appendChild(userName);
row.appendChild(cellAge);
row.appendChild(cellEmail);
This will append all of our cells into the row variable, but how do we get the row into the table?
Simple, we use .appendChild once again!
row.appendChild(index);
row.appendChild(userName);
row.appendChild(cellAge);
row.appendChild(cellEmail);
table.appendChild(row);
Aweseome! With that, we've finished our for loop! However, there is one step left.
Our table is full, but it isn't displayed on our website yet. For that, we need to refer back to the userTable varibale in the fist line of our file.
On your HTML file, you need to have a element (I use a div element) with the id of userTable on your page.
All that's left to do is append your table information into this div to display it on your site:
row.appendChild(index);
row.appendChild(userName);
row.appendChild(cellAge);
row.appendChild(cellEmail);
table.appendChild(row);
}
userTable.appendChild(table);
Congratulations! You're finished with your user loop! If you did everything right, you should have a list of users just like the example :)
If not, don't worry! I'll put my code here for you to cross check against. If you copy and paste this, it should work (assuming you have the div with userTable id)
var userTable = document.getElementById("userTable");
var table = document.createElement("table");
// Loop through each user
for (var i = 0; i < users.length; i++) {
var user = users[i];
// Create a new row for each user
var row = document.createElement("tr");
// Create table cells for each user attribute
var index = document.createElement("td");
index.textContent = i + 1; // User index
var userName = document.createElement("td");
userName.textContent = user.name;
var userAge = document.createElement("td");
userAge.textContent = user.age;
var userEmail = document.createElement("td");
userEmail.textContent = user.email;
// Append table cells to the row
row.appendChild(index);
row.appendChild(userName);
row.appendChild(userAge);
row.appendChild(userEmail);
// Append the row to the table
table.appendChild(row);
}
userTable.appendChild(table);