HTML and CSS Reference
In-Depth Information
JavaScript provides three functions to convert the primitive data types. They are:
•
String()
•
Number()
•
Boolean()
EXAMPLE
5.14
<html>
<head><title>The Conversion Functions</title></head>
<body>
<p>
<h3>Data Conversion</h3>
<script type="text/javascript">
1
var num1 = prompt("Enter a number: ","");
var num2 = prompt("Enter another number: ","");
2
var result = Number(num1) + Number(num2);
//
Convert strings to numbers
3
alert("Result is "+
result
);
4
var myString=String(num1);
5
result=myString + 200;
//
String + Number is String
6
alert("Result is "+ result); //
Concatenates 200 to the
//
result; displays 20200
7
alert("Boolean result is "+ Boolean(num2));
//
Prints true
</script>
</body>
</html>
EXPLANATION
1
The user is prompted to enter a number (see Figure 5.20). Even though the user
typed a number, JavaScript treats user input as string data and assigns it to the
variable
num1
as a string. On the next line,
num2
is assigned another string (see
Figure 5.21).
2
The JavaScript
Number()
function converts strings to numbers. After the variables
num1
and
num2
have been converted to numbers, the
+
sign will be used as an ad-
dition operator (rather than a concatenation operator), resulting in the sum of
num1
and
num2
. Unless converted to numbers, the string values
“30” + “20”
would be concatenated, resulting in
3020
.
3
The
alert
box displays the sum of the two numbers entered by the user (see
Figure 5.22).
4
The variable
num1
is converted to a string; its value is assigned to the variable,
result
.
5
The value of
myString, 20,
is concatenated to
200
and assigned to
result
. The result
is
20200
.
6
The
alert()
box displays the result from line 5.
7
The value of
num2
is converted to Boolean, either
true
or
false
. Because the value
of
num2
is not 0,
true
is displayed in the
alert()
dialog box.