Javascript Boolean Reference Type

Introduction

The Javascript Boolean type is the reference type corresponding to the boolean values.

To create a Boolean object, use the Boolean constructor and pass in either true or false:

let booleanObject = new Boolean(true); 

Boolean type overrides the valueOf() method to return a primitive value of either true or false.

The toString() method is overridden to return a string of "true" or "false".

It is confusing to use Boolean objects in Boolean expressions:

let falseObject = new Boolean(false);
let result = falseObject && true;
console.log(result); // true 

let falseValue = false;
result = falseValue && true;/*from w w  w. j  a  va 2  s  .c  o m*/
console.log(result); // false 

In this code, a Boolean object is created with a value of false.

That same object is AND with the primitive value true.

In Boolean math, false AND true equals false.

However, in this line of code, it is the object named falseObject being evaluated, not its value (false).

All objects are automatically converted to true in Boolean expressions, so falseObject actually is given a value of true in the expression.

The typeof operator returns "boolean" for the primitive but "object" for the reference.

A Boolean object is an instance of the Boolean type and will return true when used with the instanceof operator, whereas a primitive value returns false:

console.log(typeof falseObject);        // object 
console.log(typeof falseValue);         // boolean 
console.log(falseObject instanceof Boolean);  // true 
console.log(falseValue instanceof Boolean);   // false 

We should never use the Boolean reference type.

For example, the condition in the following if statement to true:

var x = new Boolean(false);
if (x) {
  // this code is executed
}

Use boolean primitive in the conditional statement.

The following if statement evaluates to false:

var x = false;
if (x) {
  // this code is not executed
}

Do not use a Boolean object to convert a non-boolean value to a boolean value.

Use Boolean as a function, or a double NOT(!) operator:

var x = Boolean(expression);     // use this...
var x = !!(expression);          // ...or this
var x = new Boolean(expression); // don't use this!



PreviousNext

Related