The Boolean
object in JavaScript is a global object and constructor function that represents boolean values: true
or false
. Here’s an overview of the Boolean
object:
1. Creating Boolean Objects:
- You can create a
Boolean
object using theBoolean()
constructor:
const boolObj = new Boolean(true);
However, it’s more common to use primitive boolean literals:
const bool = true;
2. Properties of Boolean Object:
Boolean.prototype
: Represents the prototype for theBoolean
constructor.
3. Methods of Boolean Object:
Since boolean primitives do not have methods, the Boolean
object has only one method:
.toString()
: Returns a string representing the specified Boolean object.
const boolObj = new Boolean(true);
console.log(boolObj.toString());
// Outputs: "true"
However, it’s important to note that using the Boolean
constructor to create boolean objects is generally not recommended in most cases. Instead, you should use primitive boolean literals (true
and false
) directly, as they are more efficient and sufficient for most use cases:
const bool = true;
Converting Values to Booleans:
JavaScript provides several ways to convert values to booleans:
- Boolean Conversion: Any value can be converted to a boolean using the
Boolean()
function.
console.log(Boolean(0));
// Outputs: false
console.log(Boolean(""));
// Outputs: false
console.log(Boolean(42));
// Outputs: true
console.log(Boolean("Hello"));
// Outputs: true
- Truthy and Falsy Values: In JavaScript, some values are considered “truthy” (evaluate to
true
) and others are considered “falsy” (evaluate tofalse
).
console.log(Boolean(undefined));
// Outputs: false
console.log(Boolean(null));
// Outputs: false
console.log(Boolean(0));
// Outputs: false
console.log(Boolean(""));
// Outputs: false
console.log(Boolean(NaN));
// Outputs: false
console.log(Boolean("Hello"));
// Outputs: true
console.log(Boolean(42));
// Outputs: true
console.log(Boolean([]));
// Outputs: true
Comparisons and Conditions
- The chapter JS Comparisons gives a full overview of comparison operators.
- The chapter JS If Else gives a full overview of conditional statements.
Operator | Description | Example |
---|---|---|
== | equal to | if (day == "Monday") |
> | greater than | if (salary > 9000) |
< | less than | if (age < 18) |