Borislav Hadzhiev
Sun Feb 20 2022·2 min read
Photo by Averie Woodard
Use the Boolean
object to convert a value to a boolean in Typescript, e.g.
Boolean(someValue)
. When used as a function, the Boolean
object converts the
passed in value to a boolean - true
if the value is truthy and false
if it's
a falsy value.
const str1 = 'hello'; // 👇️ const bool1: boolean const bool1 = Boolean(str1); console.log(bool1); // 👉️ true
We used the Boolean object to convert a value to a boolean.
The boolean object returns false
if the passed in value is falsy.
The falsy values in JavaScript are: false
, 0
, ""
(empty string), null
,
undefined
, NaN
(not a number).
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(10)); // 👉️ true
Note that an empty array and empty object are truthy values, whereas an empty string is falsy.
// 👇️ const bool1: true const bool1 = !!'hello'; console.log(bool1); // 👉️ true // 👇️ const bool1: false const bool2 = !!''; console.log(bool2); // 👉️ false
Using the double bang (!!) operator is the same as using the logical NOT (!) operator twice.
The logical NOT (!) operator converts a value into a boolean and inverts the result.
console.log(!'hello'); // 👉️ 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(!!10); // 👉️ true
Boolean
object, especially when working with developers who might not be familiar with the double NOT (!!) operator.