Java Reference
In-Depth Information
Currently, its value is the undefined value because you've declared only its existence to the JavaScript
engine, not any actual data. It may sound odd, but undefined is an actual primitive value in JavaScript,
and it enables you to do comparisons. (For example, you can check to see whether a variable contains
an actual value or whether it has not yet been given a value, that is, whether it is undefined.) However,
in the next line you assign myFirstVariable a string value, namely the value Hello :
myFirstVariable = "Hello";
Here you 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. You see an example
of this in the next line of code, where you use your variable myFirstVariable in the alert() function
that you saw in the previous chapter:
alert(myFirstVariable);
This causes the first alert box to appear. Next you store a new value in your 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 you 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 would run out and the system would grind 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, use the alert() function again to display the
variable's new contents:
alert(myFirstVariable);
assigning variables with the value of other variables
You've seen that you can assign a variable with a number or string, but can you 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 you have declared the two variables myVariable and
myOtherVariable and have given the variable myOtherVariable the value 22 , like this:
var myVariable;
var myOtherVariable;
myOtherVariable = 22;
you can use the following line to assign myVariable the same value as myOtherVariable
(that is, 22 ):
myVariable = myOtherVariable;
 
Search WWH ::




Custom Search