How to convert JavaScript String to Boolean

In this tutorial, let’s look at the different ways of converting a string to Boolean in JavaScript. We’ll look at a combination of pre-defined methods available in JavaScript for this exact purpose, and common operators and methods that you can modify to get the desired output.

As you know, Boolean values are true or false, and we generally get this result for some operation (mostly a comparison operation).
But, in this tutorial, let’s look at what the default Boolean value for various strings are.

The simplest conversion – the Boolean() method

The simplest way to do this conversion is by using the pre-defined Boolean() method. This method converts everything in its path, be it a string or a number, into a Boolean value.

In this tutorial, we’re focusing on string values, so let’s look at the default conversion values of that. It’s quite simple, really.

Any non-empty string will be converted to true, and empty and undefined strings will be converted to false.

Let’s look at some examples:

console.log(`Empty string to boolean: ${Boolean('')}` );
console.log(`'true' to boolean: ${Boolean('true')}` );
console.log(`undefined to boolean: ${Boolean(undefined)}` );
console.log(`'Some string' to boolean: ${Boolean('Some string')}` );
console.log(`'false' to boolean: ${Boolean('false')}` );
console.log(`' ' - string with one space to boolean: ${Boolean(' ')}` );
console.log(`Number 0 to boolean: ${Boolean(0)}` );
console.log(`string '0' to boolean: ${Boolean('0')}` );

JavaScript string to boolean

As you can see in the above examples, falsy values (empty string, the number 0, undefined) returned false).
When you ran the string ‘true’ through the Boolean() method, it returned true, but the same was true for any random string with at least a single character as well.

So, from this, we can conclude that strings with 1 character and more, regardless of what they had inside the quotes, will return true via this method. This is why we got back true for the string ‘0’ as well, which can very well be considered a false positive.

Similarly, the string ‘false’ returned a true, though we expected a false from it. The same holds true for a single space (‘ ‘). It returned true as well, because it had a character inside of it (the space).

From these examples, we can conclude that the Boolean() method returns true for non-empty strings and false for empty strings, which might not be what we want. Let’s look at how to combat the issues we saw with this method next.

Use the === operator (Strict equal to operator)

The best way to make sure you don’t get many false positives when converting a string to a Boolean is by using the strict equal to (===) operator.

This operator will only return a true if BOTH the type and the value of both the operands are the same, which is unlike the equal to (==) operator, which will return a true if JUST the value is the same, regardless of the type.

This is great for us, because now, we can make sure that we only convert the ‘true’ string to true, and the rest to false (which is what we need.

Or we can make sure to convert any non-empty string to true, except for the strings ‘false’ and ‘ ‘ (single space) and ‘’ (empty string). This way, we’ve eliminated most of the false positives for this problem.

Let’s try both examples now.

let str = 'false'; //string with false inside of it – will return false

if(str === 'true') {
    str = true;
    console.log(str);
}
else {
    str = false;
    console.log(str);
}

When you run the above lines of code, you’ll get back the Boolean value false.

Try the same for an empty string, a single space, some random string, undefined, the string ‘0’, etc. Everything will return a false.

The only time you’ll get back a true is when the string has ‘true’ in it.

The above example does return true for the string ‘true’, but it returns false for any other string. If you want to return true for random non-empty strings as well, you can change the condition like this:

let str = 'Random string'; //random string - will return true now

if(str === 'false' || str === '' || str === ' ' || str === undefined) {
    str = false;
    console.log(str);
}
else {
    str = true;
    console.log(str);
}

Now, the above code block will return a true Boolean value for any random non-empty string, except for the ‘false’, ‘’, ‘ ‘ and undefined values (which we’ve specified in the if condition).

Use toLowerCase() to make the check case insensitive

While using the string equal to operator, notice that the string needs to be in the exact case as the condition, or the comparison won’t work.

True === true is false, because the equal to operator is case sensitive. To make the entire operation case insensitive, use the toLowerCase() method to convert the string into lowercase, and then perform the check.

let str = 'True'; //string with capital True – returns true

if(str.toLowerCase() === 'true') {
    str = true;
    console.log(str);
}
else {
    str = false;
    console.log(str);
}

In the above example, we converted the string to lowercase first (which will convert True into true) and then did the comparison, which will return a true.

Use the ternary operator instead

You can use the ternary operator instead of the ‘if else’ block and save lines of code as well, as shown below:

let str = 'True';
str.toLowerCase() === 'true' ? str = true : str = false; 
console.log(str); //Boolean value true

Make the check case insensitive using regular expressions

Alternatively, instead of using the === operator, you can use the simplest form of regular expression (just the string that needs to be matched inside the regular expression) and run it through the test method to check if they match.

The test method, by default, returns a true if the string we’re searching for is found, or false if it’s not found, where true and false are the Boolean values we’re looking for.

We can use the ‘i’ flag to make the test case insensitive as well. We don’t need to use the toLowerCase() method anymore.

Let’s look at some examples:

console.log(/true/.test('true')); //true
//Case insensitive checks with the 'i' flag
console.log(/true/i.test('True')); //true

As you can see in the above examples, we can use regular expressions to mention the exact string we want compared and we can also make the test case insensitive by using the ‘i’ flag.

But there’s a problem with this method. The example below, where the string does indeed have ‘true’ in it, but it’s wrapped inside spaces, will return a false, where you might have expected a true.

console.log(/^true$/.test(' true ')); //false

I’ve wrapped the condition (true) with ^ and $ at the start and the end to indicate that the string should start with and end with true, meaning, it should only have ‘true’ in it, and nothing else, not even spaces. Since our string had leading and trailing spaces, the result of this expression is false.

There’s nothing to worry about this issue though. Just pass the string through the trim() method and you’re good to go, as shown below:

console.log(/^true$/.test((' true ').trim())); //true

Use the Double NOT (!!) to do automatic Boolean conversions

One of the best ways to convert strings to Boolean values is by using the double NOT (!!) operator. The first ! will convert the string into the negated Boolean value (as in, any non-empty string will get converted to false as the first inversion), while the second ! will bring it back to the original Boolean value.

This concept is a little difficult to explain with just words, so let me show you an example:

let str = '';
console.log(`!str of empty string is ${!str}`);
console.log(`!!str of empty string is ${!!str}`);

When you run the above lines of code, you’ll get:

JavaScript double NOT (!!) for string to boolean

This also produces false positive on the ‘false’ and ‘ ‘ strings, so create a checkpoint for those.

Don’t use new Boolean()

You might be tempted to use the new Boolean() method to convert a string to Boolean. Please don’t. I’ll explain why.

Look at the following 2 examples:

let str = '';

let bool1 = Boolean(str);
console.log(typeof bool1);

let bool2 = new Boolean(str);
console.log(bool2);
console.log(typeof bool2);

When you run the above lines of code, you’ll get:

new Boolean() method

As you can see, the type of the value converted using Boolean() is Boolean (a primitive data type), but the bool2, which holds the result of using new Boolean() on the string, has a type of object.

The first result is easier to handle, while the second is now.

This is because new Boolean creates an instance (object) of the Boolean class while Boolean() creates the primitive Boolean value, which is what we need for calculations. So, you’re better off sticking to the first method.

Use JSON.parse

You can also use the JSON.parse method to convert a ‘true’ string to the true Boolean value by default. Make sure to standardize the string by using toLowerCase() to make sure there are no errors.

Let’s look at some examples:

let bool = JSON.parse('True'.toLowerCase());
console.log(`JSON.parse on 'True' is ${bool}`); //true
bool = JSON.parse('false'.toLowerCase());
console.log(`JSON.parse on 'false' is ${bool}`); //false

As you can see, it returns the boolean value true for ‘true’ or ‘True’ and the boolean values false for ‘false’ or ‘False’.

This method looks great doesn’t it! Ofcourse it does, but there’s a caveat. This doesn’t work on converting anything other than ‘true/True’ or ‘false/False’ to Boolean.

In fact, it spits out an error if you try to parse an empty string, or a string with just spaces. Look at this:

bool = JSON.parse(' '.toLowerCase());
console.log(`JSON.parse on '' is ${bool}`);

Run the above lines of code, and you’ll get:

JSON.parse() on empty string

And try running any other non-empty string through the JSON.parse method, you’ll get back another error.

 bool = JSON.parse("Hello".toLowerCase());
console.log(`JSON.parse on '' is ${bool}`);

Run the above, and you’ll get:

JSON.parse() on strings other than 'true' and 'false'

But using JSON.parse on a number within a string will result in an automatic string to number conversion.

bool = JSON.parse('100'.toLowerCase());
console.log(`JSON.parse on '100' is ${bool}`); //100

So, as you can see, you get back the number 100 when the string ‘100’ is passed through JSON.parse().

This is a great trick but does not serve our current purpose. So, in conclusion, the JSON.parse method, when used for string to Boolean conversion, works great on strings with the actual ‘true’ and ‘false’ values, and nothing else.

That’s it! We’ve looked at various ways of converting a string to Boolean in JavaScript.
We looked at

  1. The Boolean() method
  2. The strict equal to (===) operator
  3. The ternary operator
  4. Using regular expressions with the test() method
  5. The double NOT (!!) operator and finally,
  6. The JSON.parse() method

I hope you enjoyed this article.

Leave a Comment