Borislav Hadzhiev
Mon Oct 18 2021·2 min read
Photo by Daniel Bowman
To convert a truthy or falsy value to a boolean, pass the value to the boolean
object - Boolean(myValue)
. The boolean object converts the passed in value to
true
if it's truthy, otherwise it converts it to false
.
const a = Boolean('test'); console.log(a); // 👉️ true const b = Boolean(''); console.log(b); // 👉️ false
We used the boolean object to convert two strings to booleans.
The boolean object returns false
if the passed in value is falsy.
The falsy values in JavaScript are: false
, 0
, -0
, empty string, null
,
undefined
, NaN
.
In all other cases, true
is returned.
Here are some examples of using the boolean object.
console.log(Boolean([])); // 👉️ true console.log(Boolean({})); // 👉️ true console.log(Boolean('')); // 👉️ false console.log(Boolean('false')); // 👉️ true console.log(Boolean(0)); // 👉️ false console.log(Boolean(100)); // 👉️ true
Note that an empty array and empty object are truthy values, whereas an empty string is falsy.
const a = !!'test'; console.log(a); // 👉️ true const b = !!''; console.log(b); // 👉️ false
The double bang (!!) operator is basically using the logical NOT (!) operator twice.
The logical NOT (!) operator converts a value into a boolean and inverts the result.
console.log(!'test'); // 👉️ false console.log(!''); // 👉️ true
When we use the logical NOT (!) operator twice, we:
An easy way to think about it is - we're basically converting a value to a boolean.
Here are some examples.
console.log(!![]); // 👉️ true console.log(!!{}); // 👉️ true console.log(!!''); // 👉️ false console.log(!!'false'); // 👉️ true console.log(!!0); // 👉️ false console.log(!!100); // 👉️ true
Boolean
object, especially when working with developers who might not be familiar with the double NOT (!!) operator.