Team LiB   Previous Section   Next Section

3.3 Boolean Values

The number and string data types have a large or infinite number of possible values. The boolean data type, on the other hand, has only two. The two legal boolean values are represented by the literals true and false. A boolean value represents a truth value -- it says whether something is true or not.

Boolean values are generally the result of comparisons you make in your JavaScript programs. For example:

a == 4 

This code tests to see if the value of the variable a is equal to the number 4. If it is, the result of this comparison is the boolean value true. If a is not equal to 4, the result of the comparison is false.

Boolean values are typically used in JavaScript control structures. For example, the if/else statement in JavaScript performs one action if a boolean value is true and another action if the value is false. You usually combine a comparison that creates a boolean value directly with a statement that uses it. The result looks like this:

if (a == 4)

  b = b + 1;


  a = a + 1; 

This code checks if a equals 4. If so, it adds 1 to b; otherwise, it adds 1 to a.

Instead of thinking of the two possible boolean values as true and false, it is sometimes convenient to think of them as on (true) and off (false) or yes (true) and no (false). Sometimes it is even useful to consider them equivalent to 1 (true) and 0 (false). (In fact, JavaScript does just this and converts true and false to 1 and 0 when necessary.)[3]

[3] C programmers should note that JavaScript has a distinct boolean data type, unlike C, which simply uses integer values to simulate boolean values. Java programmers should note that although JavaScript has a boolean type, it is not nearly as pure as the Java boolean data type -- JavaScript boolean values are easily converted to and from other data types, and so in practice, the use of boolean values in JavaScript is much more like their use in C than in Java.

    Team LiB   Previous Section   Next Section