Explicit Casting
Unlike PHP, JavaScript has no explicit casting of types such as
(int)
or (float)
. Instead, when you need a value to be of
a certain type, use one of JavaScriptâs built-in functions, shown in Table 14-6.
Change to type | Function to use |
Int, integer | |
Bool, Boolean | |
Float, double, real | |
String | |
Array | |
So, for example, to change a floating-point number to an integer,
you could use code such as the following (which displays the value
3
):
n = 3.1415927 i = parseInt(n) document.write(i)
Or you can use the compound form:
document.write(parseInt(3.1414927))
Thatâs it for control flow and expressions. The next chapter focuses on the use of functions, objects, and arrays in JavaScript.
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.