JavaScript Editor JavaScript Validator     JavaScript Editor 



Team LiB
Previous Section Next Section

Variables—Storing Data in Memory

Data can be stored either permanently or temporarily.

We will want to keep important data, such as the details of a person's bank account, in a permanent store. For example, when Ms. Bloggs takes 10 dollars or pounds or euros out of her account, we want to deduct the money from her account and keep a permanent record of the new balance. Information like this might be stored in something called a database. We'll be looking at databases in detail in Chapter 17.

However, there are other cases where we don't want to permanently store data, but simply want to keep a temporary note of it. Let's look at an example. Say Ms. Bloggs has a loan from BigBadBank Inc., and she wants to find out how much is still outstanding on this loan. She goes to the online banking page for loans and clicks a link to find out how much she owes. This is data that will be stored permanently somewhere. However, suppose we also provide a facility for increasing loan repayments to pay off the loan early. If Ms. Bloggs enters an increased repayment amount into the text box on the web page, we might want to show how much sooner the loan will be paid. This will involve a few possibly complex calculations, so to make it easier, we want to write code that calculates the result in several stages, storing the result at each stage as we go along, before providing a final result. Once we've done the calculation and displayed the results, there's no need to permanently store the results for each stage, so rather than use a database, we need to use something called a variable. Why is it called a variable? Well, perhaps because a variable can be used to store temporary data that can be varied.

Another bonus of variables is that unlike permanent storage, which might be saved to disk or magnetic tape, variables are held in the computer's memory. This means that it is much, much faster to store and retrieve the data.

So what makes variables good places for temporarily storing your data? Well, variables have a limited lifetime. Once your visitors close the page or move to a new one, your variables are lost, unless you take some steps to save them somewhere.

Each variable is given a name so that you can refer to it elsewhere in your code. These names must follow certain rules.

As with much of JavaScript code, you'll find that variable names are case-sensitive. For example, myVariable is not the same as myvariable. You'll find that this is a very easy way for errors to slip into your code, even when you become an expert at JavaScript.

Also, you can't use certain names and characters for your variable names. Names you can't use are called reserved words. Reserved words are words that JavaScript uses itself, for example the word var or the word with, and so reserves for its own use. You'll find a complete list of reserved words in Appendix B. Certain characters are also forbidden in variable names; for example, the ampersand (&) and the percent sign (%). Again, you'll find a full list in Appendix B. You are allowed to use numbers in your variable names, but the names must not begin with numbers. So 101myVariable is not OK, but myVariable101 is. Let's look at some more examples.

Invalid names include

Valid names include

You may wish to use a naming convention for your variables, for example one that describes what sort of data you plan to hold in the variable. You can notate your variables in lots of different ways—none are right or wrong, but it's best to stick with one of them. One common method is Hungarian notation, where the beginning of each variable name is a three letter identifier indicating the data type. For example, we may start integer variable names with int, floating-point variable names with flt, string variable names with str, and so on. However, as long as the names you use make sense and are used consistently, it really doesn't matter what you use.

Declaring Variables and Giving Them Values

Before you can use a variable, you should declare its existence to the computer using the var keyword. This warns the computer that it needs to reserve some memory for your data to be stored in later. To declare a new variable called myFirstVariable you would write

var myFirstVariable;

Note that the semicolon at the end of the line is not part of the variable name, but instead is used to indicate to JavaScript the end of a statement. This line is an example of a JavaScript statement.

Once declared, a variable can be used to store any type of data. As we said earlier, many other programming languages, called strongly typed languages, require you to declare not only the variable, but also the type of data, such as numbers or text, that it will be used to store. However, JavaScript is a weakly typed language; you don't need to limit yourself to what type of data a variable can hold.

You put data into your variables, a process called assigning values to your variables, by using the equals sign (=). For example, if you want your variable named myFirstVariable to hold the number 101, you would write

myFirstVariable = 101;

The = sign has a special name when used to assign values to a variable; it's called the assignment operator.

Try It Out – Declaring Variables

Let's look at an example in which we declare a variable, store some data in it, and finally access its contents. We'll also see that variables can hold any type of data, and that the type of data being held can be changed. For instance, we can start by storing text, then change to storing numbers, without JavaScript having any problems. Type the following code into your text editor and save it as ch2_examp1.htm.

<html>
<head>
</head>
<body>
    
<script language="JavaScript" type="text/javascript">
    
var myFirstVariable;
    
myFirstVariable = "Hello";
alert(myFirstVariable);
    
myFirstVariable = 54321;
alert(myFirstVariable);
    
</script>
    
</body>
</html>

As soon as you load this into your web browser, it should show an alert box with "Hello" in it, as shown in Figure 2-1. This is the content of the variable myFirstVariable at that point in the code.


Figure 2-1

Click OK and another alert box appears with "54321" in it, as shown in Figure 2-2. This is the new value we assigned to the variable myFirstVariable.


Figure 2-2

How It Works

Within the script block, we first declare our variable.

var myFirstVariable;

Currently, its value is the undefined value because we've only declared its existence to the computer, not actually stored any data inside it. It may sound odd, but undefined is an actual primitive value in JavaScript, and it allows us to do comparisons. (For example, we can check to see if a variable contains an actual value or if it has not yet been given a value, i.e. is "undefined".) However, in the next line we assign myFirstVariable a string value, namely the value "Hello".

myFirstVariable = "Hello";

Here we have assigned the variable a literal value, that is, a piece of actual data rather than data obtained by a calculation or from another variable. Almost anywhere that you can use a literal string or number, you can replace it with a variable containing number or string data. We see an example of this in the next line of code, where we use our variable myFirstVariable in the alert() function that we saw in the last chapter.

alert(myFirstVariable);

This causes the first alert box to appear. Next we store a new value in our variable, this time a number.

myFirstVariable = 54321;

The previous value of myFirstVariable is lost forever. The memory space used to store the value is freed up automatically by JavaScript in a process called garbage collection. Whenever JavaScript detects that the contents of a variable are no longer usable, such as when we allocate a new value, it performs the garbage collection process and makes the memory available. Without this automatic garbage collection process, more and more of the computer's memory would be consumed, until eventually the computer ran out and the system ground to a halt. However, garbage collection is not always as efficient as it should be and may not occur until another page is loaded.

Just to prove that the new value has been stored, we use the alert() function again to display the variable's new contents.

alert(myFirstVariable);

Assigning Variables with the Value of Other Variables

We've seen that we can assign a variable with a number or string, but can we assign a variable with the data stored inside another variable? The answer is yes, very easily, and in exactly the same way as giving a variable a literal value. For example, if we have declared two variables myVariable and myOtherVariable, and have given the variable myOtherVariable the value 22, like this:

var myVariable;
var myOtherVariable;
myOtherVariable = 22;

then we can use the following line to assign myVariable with the same value as myOtherVariable (that is, 22).

myVariable = myOtherVariable;

Try It Out – Assigning Variables the Values of Other Variables

Let's look at another example, this time assigning variables the values of other variables. Type the code into your text editor and save it as ch2_examp2.htm.

<html>
<body>
    
<script language="JavaScript" type="text/javascript">
    
var string1 = "Hello";
var string2 = "Goodbye";
    
alert(string1);
alert(string2);
    
string2 = string1;
    
alert(string1);
alert(string2);
    
    
string1 = "Now for something different";
    
alert(string1);
alert(string2);
    
</script>
    
</body>
</html>

Load the page into your browser, and you'll see a series of six alert boxes appear. Click OK for each one to see the next. The first two show the values of string1 and string2—"Hello" and "Goodbye," respectively.

Then we assign string2 the value that's in string1. The next two alert boxes show string1 and string2's contents; this time both are "Hello."

Finally, we change the value of string1. Note that the value of string2 remains unaffected. The final two alert boxes show the new value of string1 (Now for something different) and the unchanged value of string2 (Hello).

How It Works

The first thing we do in the script block is to declare our two variables, string1 and string2. However, notice that we have assigned them with values at the same time as we have declared them. This is a shortcut, called initializing, that saves us typing too much code.

var string1 ="Hello";
var string2 = "Goodbye";

Note that we can use this shortcut with all data types, not just strings. In the next two lines, we show the current value of each variable to the user using the alert() function.

alert(string1);
alert(string2);

Then, we assign string2 with the value that's contained in string1. To prove that the assignment really has worked, we again show the user the contents of each variable using the alert() function.

string2 = string1;
    
alert(string1);
alert(string2);

Next, we set string1 to a new value.

Список бесплатных сео инструментов
Сегодня сеть стала неплохим источником прибыли как для веб-мастеров так и для бизнеса. Все больше людей творят или заказывают сайты для того чтобы заработать в интернете. Если у вашего ресурса хороший дизайн и он наполнен нужной информацией для пользователей, он может быть практически невидим поисковыми машинами в следствие чего иметь низкий трафик. Для того чтобы изменить эту ситуацию вам нужно использовать поисковую оптимизацию.

string1 = "Now for something different";

This leaves string2 with its current value, demonstrating that string2 has its own copy of the data assigned to it from string1 in the previous step. We'll see in later chapters that this is not always the case. However, as a general rule we find that basic data types, such as text and numbers, are always copied when assigned, whereas more complex data types, like the objects that we'll come across in Chapter 4, are actually shared and not copied. For example, if we have a variable with the string "Hello" and assign five other variables with the value of this variable, then we now have the original data and five independent copies of the data. However, if it was an object rather than a string and we did the same thing, we'd find we still have only one copy of the data, but now six variables share it. Changing it using any of the six variable names would change it for all of them.

Finally, the alert() function is used to show the current values of each variable.

alert(string1);
alert(string2);

Team LiB
Previous Section Next Section


JavaScript Editor JavaScript Validator     JavaScript Editor


©

Auto Connection Manassas VA Reviews