A JavaScript Boolean represents one of two values: true or false.
Very often, in programming, you will need a data type that can only have one of two values, like
For this, JavaScript has a Boolean data type. It can only take the values true or false.
You can use the Boolean()
function to find out if an expression (or a variable) is true:
Or even easier:
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.
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);
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.
For a complete reference, go to our Complete JavaScript Boolean Reference.
The reference contains descriptions and examples of all Boolean properties and methods.
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!