JavaScript Language Essentials
[next]
JavaScript Language Essentials
Let's wade a bit deeper into the JavaScript language. In this chapter, we'll go into more detail about the basic elements of JavaScript and introduce you to other aspects of the JavaScript language, such as loops, arrays, and more about functions (don't let your eyes glaze over; we promise that it'll be easy).
You'll see how you can use JavaScript to write your Web pages for you, learn how JavaScript handles errors that the user makes, and much more.
Table 3.1. Just Enough HTML—The Basics
Tag | Meaning |
table |
Presents tabular data on a Web page |
tr |
Begins a row inside the table |
th |
Heading cells for the columns in the table |
td |
Contains each cell in the table |
Around and Around with Loops
It's common in programming to test for a particular condition and repeat the test as many times as needed. Let's use an example you probably know well: doing a search and replace in a word processor. You search for one bit of text, change it to a different text string, and then repeat the process for all of the instances of the first string in the document. Now imagine that you got a program to do it for you automatically. The program would execute a loop, which lets it repeat an action a specified number of times. In JavaScript, loops become a vital part of your scripting toolbox.
More about loops
The kind of loop that we mostly use in this book is the for
loop, named after the command that begins the loop. This sort of loop uses a counter, which is a variable that begins with one value (usually 0) and ends when a conditional test inside the loop is satisfied.
The command that starts the loop structure is immediately followed by parentheses. Inside the parentheses you'll usually find the counter definition and the way the counter is incremented (i.e., the way the counter's value is increased).
In the next several examples we're going to build a simple yet familiar application, a Bingo card. We'll use each example to show you a new aspect of JavaScript. We'll begin with an HTML page, Script 3.1. It contains the table that is the Bingo card's framework (Figure 3.1). Take a look at the script, and you'll see that the first row contains the letters at the top of the card, and each subsequent row contains five table cells. Most cells contain just a non-breaking space (using the HTML entity
); however, the third row contains the Free space, so one table cell in that row contains the word "Free". Note that each cell has an id
attribute, which the script uses to manipulate the cell contents. The id
is in the form of square0
, square1
, square2
, through square23
, for reasons that we'll explain below. At the bottom of the page, there's a link that generates a new card.
Script 3.1. This HTML page creates the skeleton for the Bingo card.
Figure 3.1 This Bingo card has randomly generated numbers, but it isn't a valid Bingo card. Yet.
[next]
URL: