JavaScript Boolean Object

The Boolean object in JavaScript is a wrapper object that can be used to represent true or false values. Although JavaScript has a primitive boolean type, the Boolean object provides methods that can be used for type conversion or coercion.

Key Features of the JavaScript Boolean Object:

Creating a Boolean Object:

This example demonstrates how to create a Boolean object and its possible values:

Example


let isActive = new Boolean(true);
let isInactive = new Boolean(false);
        
console.log(isActive);   // [Boolean: true]
console.log(isInactive); // [Boolean: false]
                    

Output

[Boolean: true]
[Boolean: false]

Using Boolean Values in Conditions:

Booleans are often used in conditional statements to check if something is true or false:

Example


let isLoggedIn = true;
        
if (isLoggedIn) {
console.log("Welcome, User!");
} else {
console.log("Please log in.");
}
                    

Output

Welcome, User!

Type Conversion to Boolean:

In JavaScript, non-boolean values can be converted to a Boolean based on their truthiness:

Example


console.log(Boolean(0));        // false
console.log(Boolean(1));        // true
console.log(Boolean(""));       // false
console.log(Boolean("Hello"));  // true
                    

Output

false
true
false
true

Boolean Comparison:

Booleans can be compared using comparison operators:

Example


let isAdult = true;
let isMinor = false;
        
console.log(isAdult === isMinor); // false
console.log(isAdult !== isMinor); // true
                    

Output

false
true

When to Use JavaScript Boolean:

The Boolean object is useful in situations where you need to work with true/false values, especially for conditions and comparisons in control flow structures like if-else statements, loops, and logical expressions.