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

Required Reading for All Couples

If you're married, about to get married, or just committed to someone for a long period of time, these three books are absolutely required reading.

I Launched a New Podcast, and I Want You to Call In

I just launched a new podcast called Design By Committee, dedicated to answering your questions about UX, product design, content, strategy and anything else tech.

Shitty Sales Have Made Product Development Harder

Shitty, one-sided sales processes have made product development much more difficult for early stage startups.

Why I'm Cold Emailing You

You might have gotten a cold email from me. Tasteless? Some people think so. Here's why I'm doing it.

How I Found Your Email

I've been cold emailing a lot of people, and many folks are surprised that I found their email. Here's where I dug it up.

Sales is User Research, Undercover

Announcement: The Most Exciting Thing I've Done

Today, I'm announcing the most exciting project I've been involved with. It's called CrowdSync, and it helps to automate paperwork, communication and logistics when dealing with groups of people. Read on for why this is so big.

Three Ways to Start Talking to Users

How to Post to Private Slack Channels from Zapier

If you automate posting to Slack via Zapier, you might need to post to a private channel. It's not entirely obvious how to do it, but actually pretty damn easy.

A Peek Inside our UX Process