JavaScript Booleans
A JavaScript Boolean represents one of two values: true or false.
Boolean Values
Very often, in programming, you will need a data type that can only have one of two values, like
- YES / NO
- ON / OFF
- TRUE / FALSE
For this, JavaScript has a Boolean data type. It can only take the values true or false.
The Boolean() Function
You can use the Boolean()
function to find out if an expression (or a variable) is true:
Or even easier:
Comparisons and Conditions
The chapter JS Comparisons gives a full overview of comparison operators.
The chapter JS Conditions gives a full overview of conditional statements.
Here are some examples:
Operator | Description | Example |
---|---|---|
== | equal to | if (day == "Monday") |
> | greater than | if (salary > 9000) |
< | less than | if (age < 18) |
The Boolean value of an expression is the basis for all JavaScript comparisons and conditions.
Everything With a "Value" is True
Everything Without a "Value" is False
JavaScript Booleans as Objects
Normally JavaScript booleans are primitive values created from literals:
let x = false;
But booleans can also be defined as objects with the keyword new
:
let y = new Boolean(false);
Example
let x = false;
let y = new Boolean(false);
// typeof x returns boolean
// typeof y returns object
Try it yourself »
Do not create Boolean objects.
The new
keyword complicates the code and slows down execution speed.
Boolean objects can produce unexpected results:
When using the ==
operator, x and y are equal:
let x = false;
let y = new Boolean(false);
Try it Yourself »
When using the ===
operator, x and y are not equal:
let x = false;
let y = new Boolean(false);
Try it Yourself »
Note the difference between (x==y) and (x===y).
Comparing two JavaScript objects always return false.
Complete Boolean Reference
For a complete reference, go to our Complete JavaScript Boolean Reference.
The reference contains descriptions and examples of all Boolean properties and methods.