Variables


Variables

When you store data in a variable, you're setting aside space for it in your program and giving it a name that you can refer to it with in your code. Unlike literals, you can manipulate and change the value stored in a variable, such as the current temperature, the value in a bank account, the current amount the user owes, and so on.

In JavaScript, you should first declare a variable before you use it, and you use the var statement to do that. This statement has been around since the beginning, as you see in Table 2.1.

Table 2.1. The var Statement

Statement

NS2

NS3

NS4

NS6

IE3a

IE3b

IE4

IE5

IE5.5

IE6

var

x

x

x

x

x

x

x

x

x

x

Here's the formal syntax of the var statement, which we'll decipher fully over the next few pages:

 var  varname  [=  value  ] [,  varname  [=  value  ] ...] 

In its simplest form, you just use the var statement to declare a variable so that you can use that variable in your code. Here's an example; in this case, I want to store the number of days left until summer vacation in a variable named numberOfDaysLeft , so I declare that variable with var :

 <SCRIPT LANGUAGE="JavaScript">  <!--  var numberOfDaysLeft  .      .      .  // -->  </SCRIPT> 

Now I'm free to assign data to this new variable, and that data will be stored in the variable. Here, I'm using the = assignment operator to store the number 262 in numberOfDaysLeft :

 <SCRIPT LANGUAGE="JavaScript">  <!--     var numberOfDaysLeft  numberOfDaysLeft = 262  .      .      .  // -->  </SCRIPT> 

Now that I've stored a value in this variable, all I have to do is to use the variable's name in code, and JavaScript will replace that name with the variable's value. For example, here's how I display the value in numberOfDaysLeft using document.write (as we saw in the preceding chapter, the + operator joins strings together):

(Listing 02-01.html on the web site)
 <HTML>      <HEAD>          <TITLE>              Working With Variables          </TITLE>      </HEAD>      <BODY>          <H1>Working With Variables</H1>          <FORM NAME="Form1">          </FORM>          <SCRIPT LANGUAGE="JavaScript">          <!--             var numberOfDaysLeft              numberOfDaysLeft = 262  document.write("Number of days until summer: " + numberOfDaysLeft + ".")  // -->          </SCRIPT>      </BODY>  </HTML> 

You can see the result in Figure 2.1, where the value in numberOfDaysLeft is displayed.

Figure 2.1. Using a variable in Netscape Navigator.

graphics/02fig01.gif

In this way, when you store data in a variable in your code, that data becomes accessible to your code. You can set the value in a variable, change the value if you want to, and access it from your code. Now we're able to start handling data in our code.

Note that we just used the var statement to declare numberOfDaysLeft ;we didn't have to say what type of data would be stored in this variable (which you must do in many programming languages). JavaScript knows what type the data is in a variable depending on the data you assign to a variable; for example, assigning 262 to numberOfDaysLeft tells JavaScript that this variable will be storing numeric data:

 numberOfDaysLeft = 262 

If I had stored a string, JavaScript would know that the variable is storing string data:

 numberOfDaysLeft = "Two hundred sixty two days left" 

You can change the type of data stored in a variable at any timejust assign new data to it. Here, I'm changing the type of data stored in numberOfDaysLeft from a number to a string:

 numberOfDaysLeft = 262  numberOfDaysLeft = "Two hundred sixty two days left" 

Tip

Actually, JavaScript is a pretty forgiving language. It's not strictly necessary to use var , although you're supposed to, to declare variables before using those variablesjust using the variables can declare them by default. I could just have used the statements numberOfDaysLeft = 262 and document.write("Number of days until summer: " + numberOfDaysLeft + ".") here. The only time JavaScript will actually insist that you declare variables before using them is when they might conflict with other variables of the same name, which we'll see more about in the next chapter.


Naming Variables

Note also the name of our first variable: numberOfDaysLeft . Here, I've put this name together using several words, and I'm using the Java variable-naming convention, which is the standard in JavaScript. That means the variable name starts with a small letter, and the first letter of each word that goes into the name is capitalized. The other standard option is to use underscores to assemble the variable name, like this: number_of_days_left . However, it's usually better to stick to the Java naming convention; JavaScript itself uses that convention to name its built-in functions, such as toUpperCase , which changes the case of a text string to upper case, as we'll see in this chapter.

You can't give a variable the same name as a JavaScript reserved word (refer back to Tables 1.2, 1.3, and 1.4). Nor can JavaScript variables start with a number, contain spaces, or any punctuation characters except underscores. (In general, the rules for legal names for JavaScript variables are the same for HTML identifiers.)

Initializing the Variable's Data

Here's what the syntax of the var statement is, as we've already seen:

 var  varname  [=  value  ] [,  varname  [=  value  ] ...] 

What does this mean? We'll see syntax statements such as this in this and the next chapter. The terms not in italic are JavaScript keywords; the terms that are in italic are placeholders where you can fill in your own items. For example, varname here is a placeholder for the name of the variable you're declaring. The square brackets, [ and ], are the standard way to indicate that something is optional in syntax statements. (You'll see this in all JavaScript documentation, so I'll use the same technique here.) Therefore, you can, optionally , write a var statement like this:

 var numberOfDaysLeft = 262 

This declares a variable and assigns it a value, all in one step. It's the same as if you had used these two statements:

 var numberOfDaysLeft  numberOfDaysLeft = 262 

Note also that, as you see in the preceding syntax statement, you can declare multiple variables in the same var statementand even initialize them, as in this example:

  var numberOfDaysLeft = 262, numberOfNightsLeft = 261, numberOfCustomersLeft = 2  document.write("Number of days until summer: " + numberOfDaysLeft + ".")          .          .          . 

This declares and initializes three variables with dataall in one var statement. This gives the same result as these three var statements:

  var numberOfDaysLeft = 262   var numberOfNightsLeft = 261   var numberOfCustomersLeft = 2  document.write("Number of days until summer: " + numberOfDaysLeft + ".")          .          .          . 

Where Do You Use the var Statement?

Here's another thing to realize: So far, I've used the var statement as the first statement in our scripts, and in fact, variable declarations must be done first thing in many languages. In JavaScript, however, you can use the var statement wherever you need it; it doesn't have to be the first statement in a script at all:

 <HTML>      <HEAD>          <TITLE>              Working With Variables          </TITLE>      </HEAD>      <BODY>          <H1>Working With Variables</H1>          <FORM NAME="Form1">          </FORM>          <SCRIPT LANGUAGE="JavaScript">          <!--  document.write("Welcome to my Web page!<BR>")   var numberOfDaysLeft   numberOfDaysLeft = 262   document.write("Number of days until summer: " + numberOfDaysLeft + ".")  // -->          </SCRIPT>      </BODY>  </HTML> 

We'll see more on this in the next chapter when we cover the for loop.



Inside Javascript
Inside JavaScript
ISBN: 0735712859
EAN: 2147483647
Year: 2005
Pages: 492
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net