HTML and CSS Reference
In-Depth Information
A weakly typed language relieves programmers from the task of assigning data types
to variables. However, this can lead to unpredictable results if you aren't careful. For
example, in JavaScript the + symbol can be used with either numeric values or text strings.
When used with numeric values, it returns the sum of the values; thus, the statement
In a weakly type language,
variables which are not
strictly tied to specific
data types are called vari-
ant data types.
varƒtotalƒ=ƒ5ƒ+ƒ4;
stores the value 9 in the total variable. When used with text strings, however, the + sym-
bol combines the strings, meaning that the statement
varƒemLinkƒ=ƒ“cadler”ƒ+ƒ“@”ƒ+ƒ“mpl.gov”;
stores the text string cadler@mpl.gov in the emLink variable. Note that when used with
both a text string and a numeric value, the + symbol treats the numeric value as a text
string; thus, the following statements
xƒ=ƒ5;
yƒ=ƒ“4”;
zƒ=ƒx+y;
result in the text string 54 being stored in the z variable, because the y variable stores 4
as a text string, not a number. This result is not readily apparent from the code without a
prior understanding of how JavaScript handles text and numeric values. This is one of the
limitations of a weakly typed language, in which data types are sometimes inferred by
the rules of the language and not explicitly set by the programmer.
To see how the + symbol works with text string variables, you'll add a third variable to
your script: the emLink variable, which will be used to store the complete e-mail address
for Catherine Adler by combining the userName variable with the emServer variable.
To create the emLink variable:
1. Return to the mpl.htm file in your text editor.
2. Directly below the command to create the emServer variable, insert the following
command, as shown in Figure 10-14:
varƒemLinkƒ=ƒuserNameƒ+ƒ“@”ƒ+ƒemServer;
Figure 10-14
creating the emLink variable
the emLink variable
combines the text
values of the userName
and emServer variables
3. Save your changes to the file.
After you've created a variable, you can use it in JavaScript statements in place of the
value it contains. For example, the following code uses the value of the libName variable
to write the text string Monroe Public Library to a Web page:
varƒlibNameƒ=ƒ“MonroeƒPublicƒLibrary”;
document.write(libName);
 
Search WWH ::




Custom Search