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

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more