Previous: Creating Functions in JavaScript Next: Controlling Your JavaScript

Working with Variables

In your scripts, you'll work with two basic types of data: literals and variables. Literals are simply values that don't change, such as 5 or "Love hurts" or 6.02. These represent different types of values that you can use directly in the assignments and computations (both of which, together, are called expressions in programming) that make up your script.

You've already had a brief introduction to variables in JavaScript, but they're worth looking at a bit more closely. Variables in JavaScript are probably easier to work with than those in many other programming and scripting languages, because you don't need to be explicit about declaring the variables and setting them with a certain type. You'll find that there are four types of values that you can work with in JavaScript: integers, floating-point numbers, text strings, and Boolean values.

Integers are plain, non-decimal values such as 4, 17, and 2546. They can be positive or negative, such as –57. Floating-point numbers are those that include a decimal point, such as 3.2, 2456.24, and 1.45674e10 (which would be 14,567,400,000 using exponent notation). Boolean values simply mean true or false; you can use these values in certain comparisons within your script.

Strings are a special type of value that represents a series of characters that appear between quotation marks. These values can be words, sentences, data series, and even numbers. The difference between a string and an integer or floating-point is that strings can't be used in arithmetic. (They can be converted to numbers when necessary, however.) For instance, City = "Miami" and Zip = "33140" are both string assignments, because they are strings of characters in quotation marks.

Variable Names

There are rules and conventions for naming variables that you should consider following when you're creating your JavaScript code.

Variable names must start with either a letter or the underscore character. Otherwise, they can be composed of upper- and lowercase letters and the digits 0–9. Variable names are case-sensitive, so myVar and Myvar are two different variables.

So, how do you pick the names? Different script writers will take different approaches, but I recommend making your names as meaningful as possible. You can often do that by compressing words together to make variable names such as NewNum or TotalSales. You can also use an underscore to create variables like oct_sales or fish_count. Either is acceptable, although I'd recommend keeping your variable names reasonably short, because you're going to have to type them repeatedly.

It's also fairly common to use short, one-letter variables in certain situations, usually when you want a "toss-away" variable that's used for counting something. Throughout the examples in this section, you'll see cases where a simple variable letter is used. As long as it's a letter, and not a number or punctuation of some kind, it's legal.

Variables, Math, and Assignments

As you might guess, particularly if you have an experience with algebra, these variables are used in a lot of math. You can add (+), subtract (-), divide (/) or multiply (*) variables and literals, such as

myNum * 5
x + 1
12%5

In that third example, you get the remainder—2—after division between the two values takes place. In fact, you'll see this sort of math going on a lot in scripts and programming. However, you may have noticed something about those examples—they're pretty much useless. Again, as with algebra, math in scripting is really only handy when you assign the result to some variable:

newNum = myNum * 5;
x = x + 1;

These are assignments, and they're used to further the cause of the script. (They're also valid JavaScript expressions, which is why each one has a semicolon at the end.) Now that the new value is assigned to a variable, it can be used later in the script.

Variable assignments can be simpler, if desired:

myName = "Mike";
x = 4;
carColor = "light blue";

JavaScript also enables you to declare a variable without immediately assigning a value to it. This can be handy when you need to create a variable, but you don't want it to have a particular value yet:

var x;
var myVariable;

By the way, you're free to declare new variables as part of an assignment, too, as long as the variable hasn't already been created. So, the following is valid:

var mileageCount = 10000;

Incrementing and Decrementing Variables

As you've seen, math is pretty easy to accomplish in JavaScript. One of the most typical operations is to increment a particular variable, sometimes to count how many times something happens within a script. One way that's done has been shown already:

x = x + 1;

The plus sign in this equation is called a binary operator because it requires two items that can be added together. In this particular instance, the old value of x is added to 1, and the result becomes the new value of x. For instance:

var y = 5;
y = y + 1;

After the first line, the value of y is 5; after the second line, the value of y is now 6.

JavaScript allows you to do this particular operation in another way, using unary operators. A unary operator requires only one operand, as in the unary increment operator:

x++;

In fact, you can increment with either x++ or ++x. The difference is in when the increment occurs. For instance, if x equals 2:

y = x++;

y will be assigned the value 2, and then x will be incremented to 3. Consider the following example, though:

y = ++x;

x is incremented first, to 3, and then that value is assigned to y, so that they both now equal 3.

Decrementing (subtracting from) variables works the same way, with both x-- and --x as possibilities. Both work similarly to x = x - 1, except that --x will decrease before being assigned.

It is also possible to assign the value to variables at the same time you increment or decrement. Generally, you would do this with an expression like the following:

x = x + 3;

However, this is also possible with the unary operators += and -=. For instance, the preceding could be written as

x += 3;

If x was originally 5, it would now equal 8. Similarly, these two expressions yield the same result:

y = y - 2;
y -= 2;

Understanding Arrays

Before we leave this discussion of variables, there's another type of variable we should discuss. It's called the array, and it's actually a technique by which you can store more than one value within the same variable name. In other words, you can create a list of values within one variable. Here's an example:

var player = new Array ("Bob", "Steve", "Marcia", "Dinah");

Now, the player variable is actually an array, meaning it's storing those four values at once. So, how do you access one of those variables? Using an index number, as in

document.writeln ("The winner is " + player[2] + "!")

Arrays are indexed from 0, so in this example, player[2] would equal "Marcia" and that name would be used in the println method. You can use a special property, called length, to determine the number of items that are stored in an array:

numPlayers = player.length

Note that, because the array index starts at zero, you can't simply use the number stored in the length property as the index. For instance, if there are 5 items in the list (and thus the length value is 5), the last item is index [4], because the first one has index [0]. So, you need to compensate for that in the script.

Once the array is created, you can use the index to add players, or you can use the index to change the value of a player using a standard assignment. This script sample shows a number of these array issues at once:

<script type="text/javascript">
<!--hide scripting
var player = new Array ("Bob", "Steve", "Marcia", "Dinah");
document.writeln ("<p>Player #3 is: " + player[2] +"<\/p>");
player[2] = "Roger";
player[4] = "Susan";
document.writeln ("<p>Player #3 is now: " + player[2] +"<\/p>");
var newIdx = (player.length - 1)
document.writeln ("<p>Our newest player is: " + player[newIdx] +"<\/p>");
// end script hiding -->
</script>

Figure 4 shows the results in a browser.

Figure 4 Here's a script that accesses different values stored in an array.

Previous: Creating Functions in JavaScript Next: Controlling Your JavaScript