Convert Truthy or Falsy values to Boolean in JavaScript

avatar

Borislav Hadzhiev

Last updated: Oct 18, 2021

banner

Photo from Unsplash

Convert Truthy or Falsy values to Boolean #

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.

index.js
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.

index.js
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.

An alternative approach, but also very common approach is to use the double bang (!!) operator.
index.js
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.

index.js
console.log(!'test'); // 👉️ false console.log(!''); // 👉️ true

When we use the logical NOT (!) operator twice, we:

  • convert the value to a boolean and flip it
  • flip the boolean again

An easy way to think about it is - we're basically converting a value to a boolean.

Here are some examples.

index.js
console.log(!![]); // 👉️ true console.log(!!{}); // 👉️ true console.log(!!''); // 👉️ false console.log(!!'false'); // 👉️ true console.log(!!0); // 👉️ false console.log(!!100); // 👉️ true
Most of the time it's better to be explicit and use the Boolean object, especially when working with developers who might not be familiar with the double NOT (!!) operator.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.