Converting JavaScript values to real booleans

Converting JavaScript values to real booleans


1 min read

One of the potential problems with a dynamically typed language, such as JavaScript is working with booleans. Sometimes a boolean value is 1, "1" or true, even a string like "hello" could be true!

I always suggest to compare values using === instead of == as there is a minor difference between them.

=== checks that the value matches, but also that the type matches.
== checks the value, but not the type.

However, when working with external data, such as from an API, you could sometimes receive true as a value, or 1, "1", etc.

Let's get to the point.

When using ! // negation operator the type returned is boolean. So a trick to easily switch any value to an actual boolean is to negate it! Here's an example.

const isTruthy = !0  
const isFalsy = !1  

Another way which could be easier to reason is to use a double negation operator !!.

const isTruthy = !!1 
const isFalsy = !!0 

Let's hope that the next API you work with gives you real boolean values so you won't have to use this.