In JavaScript, a boolean is a basic (primitive) data type. It can only have two values:
-
true
(yes) -
false
(no)
Booleans are used to control the flow of a program, especially in conditions like if
, else
, while
, and switch
.
Example: Boolean Variables
How Booleans Control Program Flow
Boolean from Comparison
When you compare values, the result is always true
or false
.
Boolean() Function
JavaScript has a Boolean() function that converts other values to either true
or false
.
Returns true
for:
-
Any non-zero number
-
Any non-empty string
-
An object or array
Returns false
for:
-
0
,-0
-
null
-
false
-
NaN
(Not a Number) -
undefined
-
''
(empty string)
Boolean Object (new Boolean()
)
You can also create a Boolean object using new Boolean()
.
But here's a trick:
Even if you create a Boolean object with false
, it still acts like true in conditions!
Boolean vs Boolean Object
Type | Created with | Type | Example |
---|---|---|---|
boolean (primitive) | true or false | "boolean" | typeof true ? "boolean" |
Boolean (object) | new Boolean() | "object" | typeof new Boolean(true) ? "object" |
These methods can be used with booleans:
Method | What It Does | Example |
---|---|---|
toString() | Converts boolean to "true" or "false" | (1 > 2).toString(); // "false" |
toLocaleString() | Like toString() , but uses browser settings | (1 > 2).toLocaleString(); // "false" |
valueOf() | Returns the real value (true or false ) | (1 > 2).valueOf(); // false |
Summary
-
true
andfalse
are called booleans. -
They're used in conditions to control what code runs.
-
Boolean()
converts other types intotrue
orfalse
. -
new Boolean()
creates an object (be careful — evennew Boolean(false)
is "truthy"). -
Use
typeof
to check the type ("boolean"
or"object"
). -
Boolean values have helpful methods like
toString()
andvalueOf()
.