0% completed
In JavaScript, the Boolean object is a wrapper for a boolean value, either true
or false
. Booleans are often used in conditions to decide the flow of control in programming. Understanding how to work with Boolean objects and values is fundamental in creating logical conditions and expressions that drive decision-making processes in your code.
While directly using Boolean objects is less common than using primitive boolean values, understanding how they work, especially how different values are converted to true or false, is crucial for effective JavaScript programming.
Syntax
The Boolean object can be created using the Boolean()
constructor, which converts a given value to its boolean equivalent:
var trueValue = new Boolean(true); var falseValue = new Boolean(false);
- Using the
new Boolean(value);
syntax, you can create a Boolean object. The value passed to the constructor determines the truthiness or falsiness of the resulting Boolean object.
Note: It's important to note that all values passed to the Boolean()
constructor, except 0
, NaN
, ""
, null
, undefined
, and false
, create an object that evaluates to true
.
Methods
Here is a list of the method associated with the Boolean object.
Method Name | Description |
---|---|
valueOf() | Returns the primitive value of a Boolean object as a boolean data type (true or false ). |
Example
Let's look at an example using the valueOf()
method:
- A Boolean object
myBool
is created with the valuetrue
. myBool.valueOf()
returns the primitive value ofmyBool
, which is the boolean valuetrue
.
Falsy Boolean Values
In JavaScript, certain values are considered "falsy," meaning they are treated as false
in Boolean contexts. These include:
false
0
(zero)""
(empty string)null
undefined
NaN
All other values are considered "truthy" and will evaluate to true
in Boolean contexts.
Example: Falsy Boolean Values
- In this example, we use an
if
statement to test a series of values:false
,0
,""
(empty string),null
,undefined
, andNaN
. - The
||
(logical OR) operator is used to chain these values together. In a Boolean context, JavaScript evaluates each operand from left to right and stops at the first truthy value. If no truthy value is found, the last value is returned. - Since all these values are falsy, the condition in the
if
statement evaluates tofalse
, and the code block associated with theif
statement is skipped. - The program then executes the
else
block, printing "All values are falsy." to the console.
.....
.....
.....
Table of Contents
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible
Contents are not accessible