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

Default Yes vs. Default No

Are you and your team members default yes, or default no? One is good for startups, the other not so much.

Check Your Echo Chamber

The people you surround yourself with create your reality. Choose carefully.

Don't Forget the Goal

There's only one thing that matters when you're building software.

How To Get a Job Offer

Want to get a job in the field you love easily? This is how.

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