Quickly Convert 0 or 1 (as a string) to a boolean


Recently, I came up against a somewhat typical situation. I was working with an API response that returned booleans as 0 or 1, instead of true or false. To make matters a bit more complicated, they were strings, not ints.

Initially, the thought was to write a little filter that took the value in, manually compared the values, and return true or false, but I stumbled across a better trick that’s much more simple. Let’s take a look:

var myFalsyValue = "0";
var myTruthyValue = "1";

!!+myFalsyValue // false
!!+myTruthyValue // true

That’s it! So, how does this work? Pretty simple, really: first the + in the operation changes the string to an integer (handy trick in an of itself). Then, the double bang (!!) performs a boolean comparison on it, converting the int to a bool as it reverses it, then reverses it back with the second bang.

Easy as that! Saved me a bunch of time, hopefully it will for you!

Related Posts

Review: Keto Diet

I recently gave the Keto (Ketogenic) Diet a try. Suffice to say...it works.

You Don't Need to Get it All Correct Immediately

Too many people wait on shit to be perfect. Get it close, leave out some stuff, and set yourself up to quickly iterate.

Using Foundation 6 in Angular 4 (or 2)

How to use Foundation for Sites 6 in Angular 4 (or any version 2+)

Great Products Need Great DevOps

In the quest for shipping great products, DevOps is often overlooked, and that's a mistake

How I Increased my Water Intake by 500%

We all need to drink more water, but it's hard to get in the habit. Here's a simple trick I used to get a 5x improvement on my intake.

Three Secrets That Made Cutting The Cord Easy

After decades of being attached at the hip to cable, I finally cut the cord, and it's been amazing. Here are three secrets that helped me get the most of it.

How to Onboard a Product Designer

If you're bringing a product designer or UX designer in to help you design your product, there's a bad way to do it, and a good way to do it. Here's how to make sure you're doing it right.

Review: Slicing Pie

Slicing Pie is a new way to think about company equity splits, and it blows away the old methods you've probably used.

When Troubleshooting, Follow the Process!

When you're trying to troubleshoot something - a car that won't start, or a business that isn't working - follow the right process.

The Art of Finding a Way

Being resourceful and relentless is one of the keys to being successful (and a great shipper). When in doubt, find a way.