The video version of this article. 📹
Every so often you will find a situation where you will want to convert values to booleans.
This is more usual these days where most linters stop
== comparisons by default.
Here are the falsy values
// 0, -0 "", 0.0, null, undefined, NaN
And for truthy, it's pretty much everything else including empty Array and Objects.
Let's show you the easy ways to convert:
const falsey = NaN; const truthy = "truth"; Boolean(falsey); // returns false Boolean(truthy); // returns true
We can use
! (not) operator to invert a value into it's inverted state. So
!truthy === false. So if we invert it twice we get the original value a boolean.
const falsey = NaN; const truthy = "truth"; // bang bang, problem solved! 🥳 !!falsey; // returns false !!truthy; // returns true
Subscribe on Codú Community