DEV Community

Cover image for 2 Quick Ways to Convert Values to Boolean in JavaScript 💻
Niall Maher
Niall Maher

Posted on

3 1

2 Quick Ways to Convert Values to Boolean in JavaScript 💻

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.

Just as a quick note 📝

In JavaScript, we have "truthy" values and "falsy" values. These are values that are considered true or false in the context of booleans.

Here are the falsy values

// 0, -0 "", 0.0, null, undefined, NaN
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Follow me on Twitter

Subscribe on Codú Community

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay