HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
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:
Boolean(10 > 9)
Or even easier:
(10 > 9)
10 > 9
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.
100
3.14
-15
"Hello"
"false"
7 + 1 + 3.14
The Boolean value of 0 (zero) is false:
let x = 0;
Boolean(x);
The Boolean value of -0 (minus zero) is false:
let x = -0;
Boolean(x);
The Boolean value of "" (empty string) is false:
let x = "";
Boolean(x);
The Boolean value of undefined is false:
let x;
Boolean(x);
The Boolean value of null is false:
let x = null;
Boolean(x);
The Boolean value of false is (you guessed it) false:
let x = false;
Boolean(x);
The Boolean value of NaN is false:
let x = 10 / "Hallo";
Boolean(x);
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
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);
When using the ===
operator, x and y are not equal:
let x = false;
let y = new Boolean(false);
Note the difference between (x==y) and (x===y).
(x == y)
true of false?
let x = new Boolean(false);
let y = new Boolean(false);
(x === y)
true of false?
let x = new Boolean(false);
let y = new Boolean(false);
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.