Last updated: Mar 4, 2024
Reading timeยท3 min
Use the Boolean()
constructor to convert an integer to a boolean, e.g.
Boolean(5)
.
The Boolean()
constructor converts integers with a value of zero to false
and all other integers to true
.
console.log(Boolean(1)); // ๐๏ธ true console.log(Boolean(0)); // ๐๏ธ false console.log(Boolean(-0)); // ๐๏ธ false console.log(Boolean(-1)); // ๐๏ธ true const num = 1; const bool = Boolean(num); console.log(bool); // ๐๏ธ true
We used the Boolean() constructor to convert integer values to boolean.
The Boolean()
constructor only converts an integer to false
if the integer
is equal to 0
.
0
is a falsy value and the Boolean()
constructor converts truthy values to true
and falsy values to false
.The falsy values in JavaScript are: false
, null
, undefined
, 0
, ""
(empty string), NaN
(not a number).
All other values are truthy and get converted to true
when passed to the
Boolean()
constructor.
An alternative approach is to use the double NOT (!!) operator.
The double NOT (!!) operator converts integers with a value of zero to false
and all other integers to true
.
console.log(!!1); // ๐๏ธ true console.log(!!0); // ๐๏ธ false console.log(!!-0); // ๐๏ธ false console.log(!!-1); // ๐๏ธ true const num = 0; const bool = !!num; console.log(bool); // ๐๏ธ false
The double NOT (!!) operator is the same as using the logical NOT (!) operator twice.
The logical NOT (!) operator:
console.log(!1); // ๐๏ธ false console.log(!0); // ๐๏ธ true
The integer 1
gets converted to the boolean true
and then flipped to get a
value of false
.
Zero is a falsy value but when converted to a boolean and flipped, we get a
value of true
.
To perform a pure boolean conversion, we have to flip the value again, by using a second logical NOT (!) operator.
console.log(!!1); // ๐๏ธ true console.log(!!0); // ๐๏ธ false
!
converts the integer to a boolean and flips the result.!
flips the boolean value, so we get a pure boolean conversion.The double NOT (!!) operator is quite concise and does the same thing as the
Boolean
constructor.
However, it's a bit harder to read if you aren't familiar with the logical NOT (!) operator.
0
Out of all integer values, only 0
converts to false
.
Therefore, we can convert an integer to a boolean by comparing it to 0
.
const bool1 = 10 !== 0; console.log(bool1); // true const bool2 = 0 !== 0; console.log(bool2); // ๐๏ธ false
We used the
strict (!==) inequality operator
to compare an integer to 0
.
If the integer is not equal to 0
, we get a value of true
, otherwise, we get
a value of false
.
This is exactly what we would expect if we had passed the integer to the
Boolean()
constructor.
This also works in the edge case where the integer is equal to -0
:
const bool3 = 0 !== -0; console.log(bool3); // ๐๏ธ false
That's because 0
is equal to -0
.
console.log(0 === -0); // ๐๏ธ true
You can learn more about the related topics by checking out the following tutorials: