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

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.

Why I Have a Cocktail at 3:30 Every Day

Every day at 3:30, I stop what I'm doing and have a cocktail. It's become an incredibly important part of my daily routine.

Everyone In a Startup Should Have This Skill

You know you need technical skills to build the product, and sales skills to sell it, but does your team have this critical skill?

Doing Things Makes You Feel Better

If you're feeling down, depressed or just in a blah mood, do something. Anything. Make a thing, clean a room. Action makes you feel better.

Review: Auth0

Auth0 is a service that provides identity as a service, so you never have to build authentication again. Here, I lay out the good and the bad.

Why I Unfollowed Everyone on Twitter

I unfollowed everyone (~4,500 people) on Twitter. Here's why I'd do such an insane thing.

How to Turn Off Facebook Live Notifications

Facebook Live is cool, but the constant notifications about new videos aren't. Here's how to turn them off and get some peace.