Casting values to booleans in JavaScript
April 6, 2022 ‐ 2 min read
Converting values to a different type in JavaScript might work a little different than expected if you come from another programming language. JavaScript doesn’t have a specific syntax for type casting, which is present in a language like PHP to name one.
Instead you instance an object of your preferred type and pass the value to cast as an argument. So in the case of booleans you would write something similar the following:
const bool = Boolean("Hello"); // => true
const ball = Boolean(""); // => false
That will convert all values to true
expect for JavaScript's falsy-values. With the falsy-values being: undefined
, null
, false
, 0
, -0
, 0n
, NaN
and ""
. Note here that an empty array or empty object are not considered falsy.
Double-negate
While using Boolean()
is at least super explicit there is a shorter syntax too which might has your preference. And that is using a double negation (!!
).
const bool = !!"Hello"; // => true
const ball = !!""; // => false
The logic behind the double negation is that using negate once (!
) will evaluate the following expression to a boolean value, but also negates it. Negating that result, which is already a boolean value, undoes the first negation.
See if you can crack the following, if you do you should be good to go when it comes to using double negation.
0 == false; // => true
0 === false; // => false
Boolean(0); // => false
Boolean(5); // => true
!0; // => true
!5; // => false
!!0; // => false
!!5; // => true