Article
JavaScript 101 - Part 2
This article was originally published by Sausage Software, makers of the HotDog Professional Web Editor. Reprinted here by permission.
Hey there, and welcome back! Last time, we took a whirlwind tour of the basics of JavaScript. We looked at statements, variables, control structures, and functions, learning what they were and how they were used. Armed with those concepts and a couple of built-in functions, we wrote a script to allow us to automatically create alternating table row colors.
In Part II, we'll flesh out our knowledge a bit by looking at a few new concepts: arrays, event handlers, and the document object model. We'll then apply these in a few practical examples that you'll be able to use in your own Web pages.
Since we'll be picking up precisely where we left off last time, you shouldn't have any trouble following along if you've come this far. The preliminaries are out of the way, so let's jump right in!
Arrays
As you begin to experiment with writing your own JavaScript, you may encounter a situation where you'd like to store a list of values. For example, you might like to work with the monthly revenue history of your company. Now, you could create a bunch of variables called revenue_month_year, but working with so many variables in an organised way would be pretty inconvenient.
Arrays offer a way of grouping such lists of data into a single variable. To illustrate, let's look at how to create an array containing the days of the week:
var days = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
The above code creates a new variable called days, an array containing seven text strings (the days of the week, in order). To access a particular value from an array, you follow the name of the array with square brackets containing the index of the value you want. The index of the first value in an array is 0, the index of the second is 1, and so on. So the following code will display the message "I can't believe I have to work on Sunday!":
alert( "I can't believe I have to work on " + days[0] + "!");
Arrays also keep track of the number of values stored inside them. This value can be accessed as arrayName.length. So the following code displays the message "There are 7 days in the week.":
alert( "There are " + days.length + " days in the week.");
Each value in an array acts just like a normal variable, which means you can update the stored values just as you would any normal variable. This allows you to create an array even though some or all of the values you want to store in it may not yet be available. To create an array of a given length but without any actual values stored in it, you use a different form of the new Array(...) syntax. Here's an alternate method to create the days array above that illustrates this:
var days = new Array(7);
days[0] = "Sunday";
days[1] = "Monday";
days[2] = "Tuesday";
days[3] = "Wednesday";
days[4] = "Thursday";
days[5] = "Friday";
days[6] = "Saturday";
A little longer, but in some situations, this can be more convenient. Notice that we specified the desired size of the array (new Array(7)).
Okay, so arrays are kinda neat, but they don't seem particularly useful yet, do they? Before we look at an example that's more interesting, we need to learn a new control structure.
In Part 1, we looked at the if and if-else control structures. These allowed you to choose whether or not to execute a piece of code (or choose between two pieces of code) based on some condition. Another control structure, called a for loop allows you to keep executing a piece of code over and over as long as some condition is true. This action of repeating the same code over and over is called looping. The general form of a for loop is as follows:
for (setup-statement; loop-condition; loop-update) {
...code to run each time through the loop...
}
setup-statement should be a command that gets run once before anything else happens. This is usually used to create and initialize a variable to count the number of times the loop has executed. loop-condition is a condition just like the condition in the if/if-else control structures. The condition is checked each time through the loop, before the code between the braces is run. If the condition is true, the code between the braces will be executed. If the condition is false, the for loop ends and execution continues following the closing brace. loop-update is a command that is run right after the code between braces and before the condition is checked for the next time through the loop.
The best way to explain how a for loop works is with a simple example. Consider the following code:
for (var i = 1; i <= 3; i++) {
document.write(i + "<br>");
}
You should remember the document.write function from Part 1, which just writes what it is given into the HTML document. i++ is a shortcut for i = i + 1. The above code will write numbers 1 through 3 with <br> tags following them so they appear on separate lines. Here's how the for loop works in this case:
setup-statement: |
Create a variable |
loop-condition: |
|
loop code: |
|
loop-update: |
i = 2; |
loop-condition: |
|
loop code: |
document.write("2 |
loop-update: |
i = 3; |
loop-condition: |
|
loop code: |
document.write("3 |
loop-update: |
i = 4; |
loop-condition: |
|
(loop ends) | |
So what does all this have to do with arrays? Returning to our previous example, let's say you want to have a table on your Web page containing a history of monthly revenues for your company. You could write the table entirely in HTML, but using a JavaScript array to store the values would be more efficient. Instead of having to make updates to the HTML code, you could just change the figures in the array and the HTML would take care of itself. What's more, you could display a "total year to date" revenue figure at the bottom of the table that would be calculated and kept up-to-date by JavaScript using the values in your array. Here's the relevant code:
<script language="JavaScript">
<!--
// Create two arrays: one to store the names of the months,
// and one to store the revenues for those months.
var months = new Array("January", "February",
"March", "April");
var revenues = new Array(12000, 9560, 11298, 12151);
//-->
</script>
<table border="1">
<tr><th>Month</th><th>Revenue (thousands of $)</th></tr>
<script language="JavaScript">
<!--
// Use a for loop to step through the two arrays and print
// the values in the table.
for (var i=0; i<months.length; i++) {
document.write("<tr><td>" + months[i] + "</td>");
document.write("<td>$" + revenues[i] + "</td></tr>");
}
//-->
</script>
</table>
<script language="JavaScript">
<!--
// Calculate the total revenue so far and display it
var totalRevenue = 0;
for (var i=0; i<months.length; i++) {
totalRevenue = totalRevenue + revenues[i];
}
document.write("Total Year to Date: $" + totalRevenue);
//-->
</script>
There are three pieces of JavaScript in the above code. The first creates the arrays to hold the names of the months and the revenue figures. The second writes the body of the table by using a for loop. The trick here is that in the code inside the loop, i is used to specify the index in our two arrays. The for loop starts with i equal to 0, then counts up until i equals the length of the months array, at which point the loop ends. The third piece of JavaScript works very similarly, but instead of printing the revenue values using document.write, it adds them all to totalRevenue, which is then used to print out the total!
Don't believe your eyes? Here's the output of the above code:
| Month | Revenue (thousands of $) |
|---|
If you're feeling ambitious, here's a challenge for you. Combine this example with the example given in Part 1 to give this table of revenues alternating row colors!
Kevin began developing for the Web in 1995 and is a highly respected technical author. He wrote