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