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;
else
  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.)[7]

[7] C programmers should note that JavaScript ...

Get JavaScript: The Definitive Guide, Fourth Edition 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.