Tuesday, October 6, 2020

JavaScript Boolean

JavaScript provides a boolean primitive type that has two values of true and false. The following example declares two variables that hold boolean values of false and true: 

let isPending = false;

let isDone = true;


When you apply the typeof operator to a variable that holds primitive boolean value, you get the boolean as the following example:

console.log(typeof(isPending)); //  boolean

console.log(typeof(isDone));    // boolean 

 

JavaScript Boolean object

In addition to the boolean primitive type, JavaScript also provides you with the global Boolean() function, with the letter B in uppercase, to cast a value of another type to boolean.


The following example shows you how to use the Boolean()  function to convert a string into a boolean value. Because the string is not empty, therefore it returns true.

let a = Boolean('Hi');

console.log(a); // true

console.log(typeof(a)); // boolean


The Boolean is also a wrapper object of the boolean primitive type. It means that when you use the Boolean constructor and pass in either true or false, you create a Boolean object.

let b = new Boolean(false);


To get the primitive value back, you call the valueOf() method of the Boolean object as follows:

console.log(b.valueOf()); // false


However, if you call the toString() method of a Boolean object, you get a string value "true" or "false". See the following example.

console.log(b.toString()); // "false"



The  typeof of Boolean object returns object, whereas the  typeof of a primitive boolean value returns boolean.

console.log(typeof foo); // boolean

console.log(typeof bar); // object



When applying the instanceof operator to a Boolean object, it returns true. However, it returns false if you apply the instanceof operator to a boolean value.

console.log(foo instanceof Boolean); // false

console.log(bar instanceof Boolean); // true


It is a good practice to never use the Boolean object because it will create much confusion especially when you use it in an expression. See the following example.

let falseObj = new Boolean(false);

if (falseObj) {

     console.log("weird part of the Boolean object");

}

How the script works.

  • First, create falseObj as a Boolean object wrapper for the false value.
  • Second, use falseObj in the  if statement. Because falseObj is an object, and JavaScript engine coerces it to a boolean value of true. As a result, the statement inside the if block is executed.