Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Using Variables

Unless you skipped the first three hours of this book, you've already used a few variables. You probably can also figure out how to use a few more without any help. Nevertheless, there are some aspects of variables you haven't learned yet. We will now look at some of the details.

Choosing Variable Names

Variables are named containers that can store data (for example, a number, a text string, or an object). As you learned earlier in this book, each variable has a name. There are specific rules you must follow when choosing a variable name:

  1. Variable names can include letters of the alphabet, both upper- and lowercase. They can also include the digits 0–9 and the underscore (_) character.
  2. Variable names cannot include spaces or any other punctuation characters.
  3. The first character of the variable name must be either a letter or an underscore.
  4. Variable names are case-sensitive—totalnum, Totalnum, and TotalNum are separate variable names.
  5. There is no official limit on the length of variable names, but they must fit within one line. (And you must be able to type the same name twice to make use of the variable.)

Using these rules, the following are examples of valid variable names:

total_number_of_fish
LastInvoiceNumber
temp1
a
_var39

Using Local and Global Variables

Some computer languages require you to declare a variable before you use it. JavaScript includes the var keyword, which can be used to declare a variable. You can omit var in many cases; the variable is still declared the first time you assign a value to it.

To understand where to declare a variable, you will need to understand the concept of scope. A variable's scope is the area of the script in which that variable can be used. There are two types of variables:

To create a global variable, you declare it in the main script, outside any functions. You can use the var keyword to declare the variable, as in this example:

var students = 25;

This statement declares a variable called students and assigns it a value of 25. If this statement is used outside functions, it creates a global variable. The var keyword is optional in this case, so this statement is equivalent to the previous one:

students = 25;

Before you get in the habit of omitting the var keyword, be sure you understand exactly when it's required. It's actually a good idea to always use the var keyword—you'll avoid errors and make your script easier to read, and it won't usually cause any trouble.

A local variable belongs to a particular function. Any variable you declare with the var keyword in a function is a local variable. Additionally, the variables in the function's parameter list are always local variables.

To create a local variable within a function, you must use the var keyword. This forces JavaScript to create a local variable, even if there is a global variable with the same name.

To better understand the types of variables and declarations better, look at Listing 4.4. This is a modified version of the Greet function example from earlier in this hour.

Example 4.4. A script using both local and global variables

<html>
<head>
<title>Local and Global Variables</title>
<script LANGUAGE="JavaScript" type="text/javascript">
var name1 = "Fred";
var name2 = "Ethel";
function Greet(who) {
alert("Greetings," + who);
    var name2 = "Barney";
}
</script>
</head>
<body>
<h1>Function Example: the Sequel</h1>
<p>Prepare to be greeted twice.</p>
<script LANGUAGE="JavaScript" type="text/javascript">
Greet(name1);
Greet(name2);
</script>
</body>
</html>

The script in Listing 4.4 uses the following variables:

Notice that the global variables are declared within the header of the HTML document. You can actually declare variables in any script in the document, but the header is a good place for global variables because it is executed first. If you attempt to use a variable before it is declared or assigned a value, it will contain the null value and may cause a browser error.

You should now understand the difference between local and global variables. If you're still a bit confused, don't worry—if you use the var keyword every time, you'll usually end up with the right type of variable.

Assigning Values to Variables

As you learned in Hour 2, "Creating a Simple Script," you can use the equal sign to assign a value to a variable. For example, this statement assigns the value 40 to the variable lines:

lines = 40;

You can use any expression to the right of the equal sign, including other variables. You have used this syntax earlier to add one to a variable:

lines = lines + 1;

Since incrementing or decrementing variables is quite common, JavaScript includes two types of shorthand for this syntax. The first is the += operator, which allows you to create the following shorter version of the above example:

lines += 1;

Similarly, you can subtract a number from a variable using the -= operator:

lines -= 1;

If you still think that's too much to type, JavaScript also includes the increment and decrement operators, ++ and --. This statement adds one to the value of lines:

lines++;

Similarly, this statement subtracts one from the value of lines:

lines--;

You can alternately use the ++ or -- operators before a variable name, as in ++lines. However, these are not identical. The difference is when the increment or decrement happens:

This difference is only an issue when you use the variable in an expression and increment or decrement it in the same statement. As an example, suppose you have assigned the lines variable the value 40. The following two statements have different effects:

alert(lines++);

alert(++lines);

The first statement displays an alert with the value 40, and then increments lines to 41. The second statement first increments lines to 41, then displays an alert with the value 41.

Share ThisShare This

Informit Network