Converting to Boolean


As you’ve seen, an if statement works by performing an evaluation of a condition. The program “branches” to one place or another depending on whether the condition evaluates to the Boolean value of true or false.

However, the types placed in the condition that’s evaluated aren’t restricted to the Boolean type. This means that it’s safe to use any type for a Boolean evaluation in a conditional statement as long as you realize that the implicit conversion forced by the evaluation will follow the rules shown in Table 3-1.

Table 3-1: Conversion to Boolean

Type

Converts to Boolean Value As Follows

Null

Converts to false

Number

Converts to false if 0, –0, +0, or NaN; otherwise, true

String

Converts to false if the string length = 0; otherwise, converts to true

Undefined

Converts to false

Try This at Home

As a puzzle, try constructing if statements that rely on the conversions shown in Table 3-1 —and verify that the conversions work in the way that I’ve said they do.




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net