Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

JavaScript Booleans

Chapter 21 12 mins

Learning outcomes:

  1. What are Booleans
  2. How to create Booleans
  3. Conversion to a Boolean using Boolean() and !!
  4. Boolean conversion rules

What are Booleans?

In computer programming, Booleans are true or false values that sit at the heart of conditional programming, executing code based on given conditions.

There are thousands of instances in programming where we need to perform certain actions once certain conditions are met.

As an example, read the following sentence: 'If it is raining outside, take an umbrella.' The condition here is: 'it is raining' and the action to be taken if the condition is met is: 'to take an umbrella'.

As another example, more relevant to us computer users, consider the following: 'If the battery is low, automatically switch off the computer.' Again you have a condition, 'the battery is low', and an action, 'switch off the computer'.

And there can be many such examples operating on the same idea — the fullfilment of a condition dictating an action.

In computers, we use Booleans to check whether some condition is met or not. All programming languages follow the same principles of Boolean and thus make conditional programming fairly consistent.

What does 'Boolean' mean?

The name 'Boolean' is given in honour of the prolific English mathematician, George Boole, based on his contributions to the mathematical discipline of Boolean algebra.

Let's now see how to create Booleans in JavaScript.

Creating Booleans

As with numbers and strings, we can create Booleans in JavaScript using literal notation.

The Boolean literals are true and false.

As we learnt in the previous part of this course, just like number literals create number primitives and string literals create string primitives, Boolean literals create ... you're right ... Boolean primitives.

Remember, both of these literals true and false are keywords in JavaScript.

In the code below, we create two variables and assign them Boolean values:

var isRainyDay = true;
var isBatteryLow = false;

An important thing to note here is the naming of the variables, starting with the word 'is'.

It's a good practice to begin the names of identifiers holding Booleans with the words 'is', 'has', or just name them after past-tense verbs. This helps us right away understand the purpose of these identifiers in the source code.

For example, isBatteryLow, isRainyDay, isExecuted (or even executed), isOK, hasAuthority, collapsed, defaultPrevented, are all examples of good names for identifiers holding Booleans.

Try NOT to name Boolean identifiers as verbs, such as run. Verbs go best with functions and methods, remember?

However, it's important to keep in mind that this isn't a hard-and-fast rule to follow; we might as well not use it on certain occasions. For instance, we're better off at naming a variable ok rather than isOK to indicate whether a particular operation in a program went alright or not.

Anyways, moving on, to check whether an arbitrary value is a Boolean, we can use the typeof operator. When used on a Boolean primitive, typeof returns the string 'boolean':

var isRainyDay = true;
var isBatteryLow = false;

console.log(typeof isRainyDay);
console.log(typeof isBatteryLow);
boolean boolean

Following is a quick task for you.

Create two Boolean variables isSubmitted and error, and assign them both a falsey Boolean value.

The term 'falsey' simply means to give the variables the value false. Following is the code that accomplishes the task above:

var isSubmitted = false;
var error = false;

Since Booleans are also a primitive type of JavaScript, we can create them using constructors as well. However, this is clearly NOT recommended ever in code.

Read on below to get a quick review on this notion.

The Boolean() constructor

As with the number and string data types in JavaScript, Booleans can also be created as objects. This requires the Boolean() constructor.

Following, we create two Boolean objects:

var isRainyDay = new Boolean(true);
var isBatteryLow = new Boolean(false);

If we inspect these values using the typeof operator, we'll get 'object' returned simply because they are objects:

var isRainyDay = new Boolean(true);
var isBatteryLow = new Boolean(false);

console.log(typeof isRainyDay);
console.log(typeof isBatteryLow);
object object

Despite the fact that the Booleans here are created using a constructor, we have to provide the literals true or false anyways. So, there's really no benefit of using new Boolean(), and we even shouldn't!

Now if you're thinking of the purpose of the Boolean() constructor and Boolean objects in JavaScript, know that it's the same as the purpose of the Number() and the String() constructors.

That is, the Boolean() constructor is meant to be called automatically, internally by the JavaScript engine when the need be, for the purpose of autoboxing (remember this?).

To learn more about this, consider the following sections from this course:

Re-emphasizing on it, never ever use new Boolean() in your code! It makes code verbose and ugly, and is not even meant to be used manually.

Things to note

  1. All relational operators return Booleans, always:

    typeof (1 == 1)
    "boolean"
    typeof (1 < 2)
    "boolean"
    typeof (1 > 2)
    "boolean"
    typeof (1 === 1)
    "boolean"
  2. Logical operators return Booleans depending on the operator, the operands, and the order of the operands:

    For example, consider the following:

    true && 1
    1
    1 && true
    true

    true && 1 yields 1 while the same operator called on the same values only with the order of the values changed, in 1 && true, returns true. Recall that this happens because of the way && works.

    In particular, && evaluates it first operand and returns it if it's falsey, otherwise returns the second operand.

    Another example follows of &&:

    null && false
    null
    false && null
    false

    In null && false, since the first operand null is falsey, it gets returned right away. So is the case with false && null, whereby false gets returned rightaway.

Converting to Boolean

While developing JavaScript programs, there'll be a multitude of instances where we'll want to go from a given data type to a Boolean. In this section, we'll see how to do just that.

There are mainly two ways for converting a value into a Boolean:

  • Using the Boolean() function (not the constructor)
  • Using double negation (!!)

Let's start with the first one.

The Boolean() function

The Boolean() function, when called with an arbitrary value, returns back its corresponding Boolean equivalent (based on rules which we shall see in the next section).

Consider the code below where we convert a string into a Boolean:

var str = 'Hello World!';
var strBool = Boolean(str);

console.log(strBool);
true

As we shall see shortly below, a non-empty string always gets converted to a truthy Boolean, likewise strBool here holds the value true.

Double negation (!!)

Recall the negation operator (!) from the JavaScript Operators chapter? It negates its given operand and returns back a Boolean.

A naive idea to use this operator for converting a value into a Boolean is to use the operator twice, hence the name double negation.

In the first instance, it returns a negated Boolean; in the second instance, it negates this negated value to get back the initial Boolean value.

What an elegant approach.

Following we rewrite the code above using Boolean() to instead use !!:

var str = 'Hello World!';
var strBool = !!(str);

console.log(strBool);
true

As expected, the result is the same — true.

Now deciding between which of these should you use, well it's more about preference. If you like Boolean(), go with it. If you like !! more, probably because it's easier to type, go with it.

Whatever you choose, just make sure to remain consistent with it throughout your JavaScript programs. The last thing you want in your code is to have a mix of Boolean() and !!.

Boolean conversion rules

In this respect, it's worthwhile understanding the rules of converting given values into Booleans in JavaScript.

This is important because different languages usually have different conversion rules, and we must be aware of these rules in order to make sure that we know how our programs interact and execute.

Rules for numbers

All numbers except for 0 and NaN get converted to the Boolean value true. The numbers 0 and NaN get converted to false. Quite basic, ain't it?

Boolean(0)
false
Boolean(-0)
false
Boolean(0.001)
true
Boolean(-0.5)
true
Boolean(1000)
true
Boolean(Infinity)
true
Boolean(NaN)
false

Rules for strings

All strings except for the empty string ('', "", ``) get converted to true. The empty string gets converted to false:

Boolean('0')
true
Boolean(' ')
true
Boolean('')
false

Rules for undefined and null

Expectedly, both undefined and null convert to the Boolean false:

Boolean(undefined)
false
Boolean(null)
false

Rules for objects

It's very easy with converting objects in JavaScript to Booleans — every object gets converted to true, even the one without any properties:

Boolean([])
true
Boolean({})
true
Boolean({ x: 0 })
true
Boolean(new Boolean(false))
true

Notice the last statement here: we're converting a Boolean object with the value false into a Boolean (primitive). One might expect that since the object wraps the value false, its conversion would yield false. However, that's NOT the case.

The reason isn't hard to understand. new Boolean(false) returns an object and because all objects convert to true, this one converts to true as well.