Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book


A variable can be thought of as a named “pigeon-hole” where we keep a particular piece of data. Such data can take many different forms—an integer or decimal number, a string of characters, or various other data types discussed later in this hour or in those that follow. Our variables can be called pretty much anything we want, so long as we only use alphanumeric characters, the dollar sign $, or underscores in the name.

Let’s suppose we have a variable called netPrice. We can set the value stored in netPrice with a simple statement:

netPrice = 8.99;

We call this assigning a value to the variable. Note that we don’t have to declare the existence of this variable before assigning a value, as we would have to in some other programming languages. However, doing so is possible in JavaScript by using the var keyword, and in most cases is good programming practice:

var netPrice;
netPrice = 8.99;

Alternatively we can combine these two statements conveniently and readably into one:

var netPrice = 8.99;

To assign a character string as the value of a variable, we need to include the string in single or double quotes:

var productName = “Leather wallet”;

We could then, for example, write a line of code sending the value contained in that variable to the window.alert method:


The generated dialog would evaluate the variable and display it (this time, in Mozilla Firefox) as in Figure 2.1.

Figure 2.1

Figure 2.1 Displaying the value of variable productName

  • + Share This
  • 🔖 Save To Your Account