Convert Truthy or Falsy values to Boolean in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 18 20212 min read

banner

Photo by Daniel Bowman

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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee