O'Reilly logo

Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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.

Table 14-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.1414927))

That’s it for control flow and expressions. The next chapter focuses on the use of functions, objects, and arrays in JavaScript.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required