Home » Programming » Javascript » Javascript String Boolean

Converting String to Boolean in JavaScript, With Examples

This tutorial will show you how to convert a string value to boolean in JavaScript, with working code examples for several situations.

Why Are You Converting Strings to Booleans?

Really, you should not be storing boolean data in a string, but there are several scenarios where it can arise:

  • Boolean values arising from user input
  • Values taken from HTML form elements, which can only contain string values
  • Data taken from poorly formatted third party sources, like APIs or CSV files

Once you have data containing boolean values as strings, you must determine what form those strings take, and what will be considered a TRUE value.

How To True/False Boolean String Values in JavaScript

There is no real need for a re-usable function for this task – converting from a string value to a boolean value is simply the result of a single comparison.

In the below example, the expected value for a TRUE value in a string is “true” – the string value to convert is compared to this expected value, and a boolean value is returned based on whether it is a match:

var stringValue = "true";
var booleanValue = (stringValue === "true"); // Results in a boolean value of TRUE as it is a match for "true"

var stringValue = "false";
var booleanValue = (stringValue === "true"); // Results in a boolean value of FALSE as it is not a match for "true"

Similarly, if you are expecting a “1” for the value of true (and a “0” for false), as some boolean values as stored numerically and may have been converted to strings:

var stringValue = "1";
var booleanValue = (stringValue === "1"); // Results in a boolean value of TRUE as it is a match for "1"

var stringValue = "0";
var booleanValue = (stringValue === "1"); // Results in a boolean value of FALSE as it is not a match for "1"

You must use the strict equality === operator to ensure both the value of the variable and the type are the same when making the comparison – otherwise loose comparisons may result in unexpected behaviour.

Keep Your Types in Order

If you are generating your own data and storing boolean values as strings, consider storing them as a boolean type value, or using a format that supports boolean values. Type errors are a common point of failure in JavaScript applications, so keeping your data typed correctly, or converting them to the correct type as early and infrequently as possible, can go a long way to reducing the amount of debugging you will have to do later on.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment