Skip to content

JavaScript Boolean Constructor

  • by

The JavaScript Boolean Constructor is a built-in function that allows the creation of Boolean objects, representing boolean values of either true or false.

new Boolean(value)

The Boolean() function in JavaScript can be called with or without the new keyword, and it does have different effects depending on how it is used.

When Boolean() is called a function without the new keyword, it is used as a conversion function. It takes an argument and converts it to a boolean value. The return value will be the primitive boolean value (true or false), not a Boolean object.

var boolValue = Boolean("Hello");
console.log(boolValue);  // Output: true
console.log(typeof boolValue);  // Output: boolean

On the other hand, when Boolean() is called as a constructor with the new keyword, it creates a Boolean object. The return value will be an instance of the Boolean object.

var boolObj = new Boolean(true);
console.log(boolObj);  // Output: [Boolean: true]
console.log(typeof boolObj);  // Output: object

However, it is generally recommended to utilize the primitive boolean values directly, as the usage of Boolean objects is less common and may introduce unnecessary complexity.

JavaScript Boolean Constructor example

Simple example code that demonstrates the usage of the JavaScript Boolean constructor:

// Creating Boolean objects using the constructor
var boolObj1 = new Boolean(true);
var boolObj2 = new Boolean(0);
var boolObj3 = new Boolean("hello");

console.log(boolObj1);  // [Boolean: true]
console.log(boolObj2);  // [Boolean: false]
console.log(boolObj3);  // [Boolean: true]

// Checking the types of the created objects
console.log(typeof boolObj1);  object
console.log(typeof boolObj2);  object
console.log(typeof boolObj3);  object

// Accessing the primitive value of the Boolean objects
console.log(boolObj1.valueOf());  //true
console.log(boolObj2.valueOf());  //false
console.log(boolObj3.valueOf());  //true

// Using the Boolean objects in conditional statements
if (boolObj1) {
  console.log("boolObj1 is truthy");
} else {
  console.log("boolObj1 is falsy");  // This won't be executed

if (!boolObj2) {
  console.log("boolObj2 is falsy");
} else {
  console.log("boolObj2 is truthy");  // This won't be executed


JavaScript Boolean Constructor

In this example, we create Boolean objects using the constructor with different initial values. We then demonstrate the types of the created objects, access their primitive values using valueOf(), and use them in conditional statements to evaluate their truthiness or falseness.

Do comment if you have any doubts or suggestions on this JS Boolean topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading