Java Reference
In-Depth Information
Click OK and another alert box appears with 54321 in it, as shown in Figure 2-2. This is the new value
you assigned to the variable myFirstVariable.
Figure 2-2
Within the script block, you fi rst declare your variable.
var myFirstVariable;
Currently, its value is the undefined value because you've declared only its existence to the computer,
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 if a variable contains an actual value
or if it has not yet been given a value, that is, if it is undefi ned.) 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 last chapter.
alert(myFirstVariable);
This causes the fi rst 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 collec-
tion process, more and more of the computer's memory would be consumed, until eventually the com-
puter would run out and the system would grind to a halt. However, garbage collection is not always as
effi cient 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 vari-
able's new contents.
alert(myFirstVariable);
Search WWH ::




Custom Search