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:
- True and False Values: The Boolean object represents a value that can either be true or false.
- Type Conversion: The Boolean object can be used to convert other types (like strings or numbers) into a boolean value based on their truthiness.
- Comparison Operations: Booleans are commonly used in conditional statements to determine whether a condition is true or false.
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: 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
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
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
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.