How To Convert a string to a boolean in JavaScript?

Several ways are available to convert a string to a boolean, depending on how we want the conversion.

You can convert a String to a boolean in Javascript using the var isBoolean=Boolean(str) statement.

In this tutorial, you’ll learn different methods to convert string to boolean, and when to use the methods.

If You’re in Hurry…

You can use the below code snippet to convert the string variable to boolean.

Code

    var str='true';
    var isBoolean= (str === 'true'); 
    console.log(typeof isBoolean); 

Output

When you check the console, you will find the variable isBoolean will be of type boolean.

boolean

If You Want to Understand Details, Read on…

When working with HTML elements, few elements only deal with boolean type values, and you may have string data to process.

You have to convert the string to boolean in those scenarios to make it compatible.

For example, when you store value in hidden input fields in HTML, it becomes a string. If you want to use this hidden input field value on some elements that accept boolean values, you need to convert the string value to boolean.

Let us discuss the different methods to convert String to boolean.

Using String Comparison

The easiest way to convert a string value to a boolean value is by comparing the string value with ‘true’.

Code

var str='true';
var isBoolean= (str === 'true'); 
console.log("Value of isBoolean: "+ isBoolean); 
console.log("Type of isBoolean: "+ typeof isBoolean); 

Note: This method is case sensitive. In this approach, you will be doing an exact match of string comparison.

You’ll see the below output in the console.

Output

    Value of isBoolean:  true
    Type of isBoolean: boolean

Stringvariable(str) is compared against string value true, and it returns true if it matches exactly.

Now let us see another example. Here the variable str holds value True.

Code

    var str='True';
    var isBoolean= (str === 'true'); 
    console.log("Value of isBoolean: "+ isBoolean); 
    console.log("Type of isBoolean: "+ typeof isBoolean); 

Since True and true are in a different cases, the comparison returns false.

Output

    Value of isBoolean: false
    Type of isBoolean: boolean

Now, you’ll see how to compare in a case insensitive way.

You will have to convert the string value to equivalent javascript letter casing before comparing it with conditional string value.

Code

    var str='True';
    var isBoolean= (str.toLowerCase() === 'true'); 
    console.log("Value of isBoolean: "+ isBoolean); 
    console.log("Type of isBoolean: "+ typeof isBoolean);

Now the output will be true because both the strings are in the same case.

Output

    Value of isBoolean: true
    Type of isBoolean: boolean

string str value is converted to lower case characters using toLowerCase() javascript method in order to match the conditional stringvalue true.

Note: using toLowerCase() for comparison will throw an error if the string is undefined or null.

If a condition check fails in a string comparison, it will return false.

Code

    var str='jsowl';
    var isBoolean=(str === 'true');
    console.log("Value of isBoolean: "+ isBoolean); 
    console.log("Type of isBoolean: "+ typeof isBoolean);

Output

    Value of isBoolean: false
    Type of isBoolean: boolean

This is how you can use the string comparison approach to convert string to boolean.

Using Boolean Constructor

In this approach, You will have to pass the string value to the Boolean constructor, and it will return a boolean value.

Code

    const str = 'false';
    var isBoolean=Boolean(str);  
    console.log("Value of isBoolean: "+ isBoolean); 
    console.log("Type of isBoolean: "+ typeof isBoolean);

Output

Value of isBoolean: true
Type of isBoolean: boolean

Converting any string using the Boolean constructor approach will return true except the Falsy Values.

Falsy Values:
Javascript has 6 falsy values, and converting these values to boolean will always return false.

Below are the 6 falsy values,

1. null 
2.  0
3.  false
4. NaN 
5. undefined
6. "" - (empty string)

Example

    Boolean(null); // false 
    Boolean(0); // false 
    Boolean(false); // false 
    Boolean(NaN); // false 
    Boolean(undefined); // false 
    Boolean(""); // false


Converting string to boolean using the new Boolean constructor approach is not recommended because it comes with certain disadvantages, as listed below,

It is preferred to use primitive types over object types because the new Boolean will return an object type instead of a boolean.

  • Primitive types are immutable, making it cheaper to share references. It will be just ‘true’ or ‘false’.

Code

    var str = 'str';
    // Not recommended
    typeof new Boolean(str); // returns object  
    // Preferred 
    typeof Boolean(str); // returns boolean

Using Double Not Syntax

Double Not Syntax works similarly to the Boolean constructor. The only difference is, it is easy to use because of its simple syntax, but most developers would easily remember Boolean constructors better.

Code

    var str='True';
    var isBoolean=!!(str);  
    console.log("Value of isBoolean: "+ isBoolean); 
    console.log("Type of isBoolean: "+ typeof isBoolean);

Output:

    Value of isBoolean: true
    Type of isBoolean: boolean

First, Not(!) will compel the value of boolean and inverse it. Anything will be false now, So to reverse the value to true, we add one more Not(!) and put it together as !!.

    var str = 'True';
    // Single Not
    !str; //false
    // Double Not      
    !!str; // true

Using JSON.parse()

You can use JSON (built-in javascript object) and use the parse method of JSON to convert string to boolean (either true/false).

Code

    var str='True';
    var isBoolean=JSON.parse(str.toLowerCase()); 
    console.log("Value of isBoolean: "+ isBoolean); 
    console.log("Type of isBoolean: "+ typeof isBoolean);

Output:

    Value of isBoolean: true
    Type of isBoolean: boolean

Using JSON.parse() to convert string to boolean, you can only pass ‘ true/false’ as string values, and anything other than ‘true/false’ will throw an error JSON syntax error.
Code

    var str='True';
    var isBoolean=JSON.parse(str); 

Output:

    "Uncaught SyntaxError: Unexpected token T in JSON at position 0."

Using Regex()

You can also use a simple regular expression to validate a string based on a specific condition; if this particular condition met, it returns true or else false.

Code

    var str='true';
    var isBoolean=(/true/i).test(stringValue) ;  
    console.log("Value of isBoolean: "+ isBoolean); 
    console.log("Type of isBoolean: "+ typeof isBoolean);

Output:

    Value of isBoolean: true
    Type of isBoolean: boolean

Using switch-case

Switch-case conversion can be used in places where multiple selective conditions need to be handled to determine a boolean value.

Code

    var str='true';
    var isBoolean=getBooleanUsingSwitchCase(str); 
    console.log("Value of isBoolean: "+ isBoolean); 
    console.log("Type of isBoolean: "+ typeof isBoolean);

    function getBooleanUsingSwitchCase(value){ 
        switch(value) { 
            case true: 
            case "true": 
            case 1: 
            case "1": 
            case "on": 
            case "yes": 
                return true; 
            default: 
                return false; 
        }
    }

Output

    Value of isBoolean: true
    Type of isBoolean: boolean

In the above example, all the input value with either of the conditional values(true/”true”/1/”1″/” on “/”yes” ) will return a boolean value as true, and in other cases, it will return boolean false.

Using the ternary operator

This is a simple conditional check to determine the return value(true/false).

Code

    var str= "true";
    let isBoolean= str.toLowerCase() == 'true' ? true : false;
    console.log("Value of isBoolean: "+ isBoolean); 
    console.log("Type of isBoolean: "+ typeof isBoolean);

Output:

    Value of isBoolean: true
    Type of isBoolean: boolean

JSfiddle

This tutorial is available in this JSFiddle.

Conclusion

string to boolean conversion could be a problem while working with dynamic web pages because specific HTML form fields will only accept string values.
Sometimes, you require boolean type data to handle particular situations. So you may need some string To boolean conversion techniques to handle those situations.

In this tutorial, you’ve learned how to convert a string to a boolean in Javascript. You’ve also known different ways to achieve string to boolean conversion.

If you’ve any questions, please comment below.

You May Also Like

2 thoughts on “How To Convert a string to a boolean in JavaScript?”

Leave a Comment