HTML and CSS Reference
In-Depth Information
EXPLANATION
(
CONTINUED
)
3
The variable called
age
is not assigned an initial value. The
var
keyword is re-
quired. Without it, the program produces errors, shown in the output for Firefox
and Explorer, in Figure 3.4 and Figure 3.5 (on page 63), respectively.
4
This line will not be printed until the variable called
age
is defined properly. Just
use the
var
keyword as good practice, even if it isn't always required!
Figure 3.4
Firefox error (JavaScript Error Console). The variable
age
was
referenced twice on lines 6 and 16 in the actual program (lines numbered 3 and 4
in Example 3.5). Program was tested twice.
Remember, strongly typed languages like C++ and Java require that you specify the type
of data you are going to store in a variable when you declare it, but JavaScript is loosely
typed. It doesn't expect or allow you to specify the data type when declaring a variable.
You can assign a string to a variable and later assign a numeric value. JavaScript doesn't
care and at runtime, the JavaScript interpreter will convert the data to the correct type.
Consider the following variable, initialized to the floating-point value of 5.5. In each suc-
cessive statement, JavaScript will convert the type to the proper data type (see Table 3.3).