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 15-6.

Table 15-6. JavaScript’s type-changing functions

Change to type

Function to use

Int, Integer

parseInt()

Bool, Boolean

Boolean()

Float, Double, Real

parseFloat()

String

String()

Array

split()

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.1415927))

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, and JavaScript 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.