buy the book to support the author.

Chapter 10. Booleans

The primitive boolean type comprises the values true and false:

  1. > typeof false
  2. 'boolean'
  3. > typeof true
  4. 'boolean'

Converting to Boolean

Values are converted to booleans as follows:

Value Converted to boolean
undefined false
null false
A boolean Same as input (nothing to convert)
A number 0, NaNfalse
other numbers → true
A string ''false
other strings → true
An object true (always!)

Manually Converting to Boolean

There are three ways any value can be converted to a boolean:

Boolean(value) (Invoked as a function, not as a constructor)
value ? true : false
!!value A single “not” converts to negated boolean; use twice for the nonnegated conversion.

I prefer Boolean(), because it is more descriptive. Here are some examples:

  1. > Boolean(undefined)
  2. false
  3. > Boolean(null)
  4. false
  5.  
  6. > Boolean(0)
  7. false
  8. > Boolean(1)
  9. true
  10. > Boolean(2)
  11. true
  12.  
  13. > Boolean('')
  14. false
  15. > Boolean('abc')
  16. true
  17. > Boolean('false')
  18. true

Truthy and Falsy Values

Wherever JavaScript expects a boolean, you can provide any kind of value and it is automatically converted to boolean. Thus, there are two sets of values in JavaScript: one set is converted to false, while the other set is converted to true. These sets are called falsy values and truthy values. Given the preceding table, the following are all falsy values:

  • undefined, null
  • Boolean: false
  • Number: 0, NaN
  • String: ''

All other values—including all objects, even empty objects, empty arrays, and new Boolean(false)—are truthy. Because undefined and null are falsy, you can use the if statement to check whether a variable x has a value:

  1. if (x) {
  2. // x has a value
  3. }

The caveat is that the preceding check interprets all falsy values as “does not have a value,” not just undefined and null. But if you can live with that limitation, you get to use a compact and established pattern.

Pitfall: all objects are truthy

All objects are truthy:

  1. > Boolean(new Boolean(false))
  2. true
  3. > Boolean([])
  4. true
  5. > Boolean({})
  6. true

That is different from how objects are converted to a number or string, where you can control the result by implementing the methods valueOf() and toString():

  1. > Number({ valueOf: function () { return 123 } })
  2. 123
  3. > String({ toString: function () { return 'abc' } })
  4. 'abc'

History: Why are objects always truthy?

The conversion to boolean is different for historic reasons. For ECMAScript 1, it was decided to not enable objects to configure that conversion (e.g., via a toBoolean() method). The rationale was that the boolean operators || and && preserve the values of their operands. Therefore, if you chain those operators, the same value may be checked multiple times for truthiness or falsiness. Such checks are cheap for primitives, but would be costly for objects if they were able to configure their conversion to boolean. ECMAScript 1 avoided that cost by making objects always truthy.

Logical Operators

In this section, we cover the basics of the And (&&), Or (||), and Not (!) logical operators.

Binary Logical Operators: And (&&) and Or (||)

Binary logical operators are:

  • Value-preserving
  • They always return either one of the operands, unchanged:
  1. > 'abc' || 123
  2. 'abc'
  3. > false || 123
  4. 123
  • Short-circuiting
  • The second operand is not evaluated if the first operand already determines the result. For example (the result of console.log is undefined):
  1. > true || console.log('Hello')
  2. true
  3. > false || console.log('Hello')
  4. Hello
  5. undefined

That is uncommon behavior for operators. Normally, all operands are evaluated before an operator is invoked (just like for functions).

Logical And (&&)

If the first operand can be converted to false, return it. Otherwise, return the second operand:

  1. > true && false
  2. false
  3. > false && 'def'
  4. false
  5. > '' && 'def'
  6. ''
  7. > 'abc' && 'def'
  8. 'def'

Logical Or (||)

If the first operand can be converted to true, return it. Otherwise, return the second operand:

  1. > true || false
  2. true
  3. > true || 'def'
  4. true
  5. > 'abc' || 'def'
  6. 'abc'
  7. > '' || 'def'
  8. 'def'

Pattern: providing a default value

Sometimes there are situations where a value (a parameter, the result of a function, etc.) can be either a nonvalue (undefined, null) or an actual value. If you want to provide a default value for the former case, you can use the Or operator:

  1. theValue || defaultValue

The preceding expression evaluates to theValue if it is truthy and to defaultValue otherwise. The usual caveat applies: defaultValue will also be returned if theValue has a falsy value other than undefined and null. Let’s look at three examples of using that pattern.

Example 1: a default for a parameter

The parameter text of the function saveText() is optional and should be the empty string if it has been omitted:

  1. function saveText(text) {
  2. text = text || '';
  3. ...
  4. }

This is the most common use of || as a default operator. Consult Optional Parameters for more on optional parameters.

Example 2: a default for a property

The object options may or may not have the property title. If it is missing, the value 'Untitled' should be used when setting the title:

  1. setTitle(options.title || 'Untitled');

Example 3: a default for the result of a function

The function countOccurrences counts how often regex matches inside str:

  1. function countOccurrences(regex, str) {
  2. // Omitted: check that /g is set for `regex`
  3. return (str.match(regex) || []).length;
  4. }

The problem is that match() (see String.prototype.match: Capture Groups or Return All Matching Substrings) either returns an array or null. Thanks to ||, a default value is used in the latter case. Therefore, you can safely access the property length in both cases.

Logical Not (!)

The logical not operator ! converts its operand to boolean and then negates it:

  1. > !true
  2. false
  3. > !43
  4. false
  5. > !''
  6. true
  7. > !{}
  8. false

Equality Operators, Ordering Operators

The following operators are covered elsewhere:

The Function Boolean

The function Boolean can be invoked in two ways:

  • Boolean(value)
  • As a normal function, it converts value to a primitive boolean (see Converting to Boolean):
  1. > Boolean(0)
  2. false
  3. > typeof Boolean(false) // no change
  4. 'boolean'
  • new Boolean(bool)
  • As a constructor, it creates a new instance of Boolean (see Wrapper Objects for Primitives), an object that wraps bool (after converting it to a boolean). For example:
  1. > typeof new Boolean(false)
  2. 'object'

The former invocation is the common one.