Using Variables and Built-in Functions to Update Your Web Pages Automatically - Page 2
Using Variables and Built-in Functions to Update Your Web Pages Automatically
Variables Store Information
Syntax of Variables
Figure 2-3: Defining and using variables
The first word, var, introduces a variable for the first time—you don't need to use it after the first instance, no matter how many times you employ the variable in the script.
Note: Many people don't use var in their code. Although most browsers let you get away without it, it's always a good idea to put var in front of a variable the first time you use it. (You'll see why when I talk about writing your own functions in Chapter 6.)
Notice that the variable name in line 8 is pretty long—unlike algebraic variables, it's not just a single letter like
If you name your variables descriptively, your code will be easier to understand while you're writing it, and much easier to understand when you return to it later for revision or enhancement. Also, no matter which programming language you use, you'll spend about 50 percent of your coding time finding and getting rid of your mistakes. This is called debugging—and it's a lot easier to debug code when the variables have descriptive names. You'll learn more about debugging in Chapter 14.
Arithmetic with Variables
Line 12 in Figure 2-3 introduces a new variable called
seconds_per_day and sets it equal to the product of the other three variables using an asterisk (*), which means multiplication. A plus sign (+) for addition, a minus sign (-) for subtraction, and a slash (/) for division represent the other major arithmetic functions.
So now you have a page that knows how many seconds there are in a day. Big deal, right? Wouldn't it be better if you could tell your visitors what the answer is? Well, you can, and it's not very hard.