Categories
boolean-expression boolean-operations javascript string-conversion

How can I convert a string to boolean in JavaScript?

3226

Can I convert a string representing a boolean value (e.g., ‘true’, ‘false’) into a intrinsic type in JavaScript?

I have a hidden form in HTML that is updated based upon a user’s selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.

The only way I could find to determine the field’s boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

Is there a better way to accomplish this?

18

  • 95

    “Is there a better way to accomplish this?” – there is certainly a worse way 😀 string=(string==String(string?true:false))?(string?true:false):(!string?true:fa‌​lse);

    Apr 16, 2015 at 10:25

  • 11

    Easily handle strings and bools: function parseBool(val) { return val === true || val === "true" }

    Sep 10, 2015 at 14:24

  • 3

    @Mark function checkBool(x) { if(x) {return true;} else {return false;} }

    – Sebi

    Nov 29, 2016 at 15:10


  • 3

    @Sebi: You forgot to document it: if (checkBool(x) != false) { ... } else { ... }

    Nov 29, 2016 at 18:21

  • 7

    !!(parseInt(value) || value === "true")

    Feb 22, 2017 at 3:58

4544

Do:

var isTrueSet = (myValue === 'true');

using the identity operator (===), which doesn’t make any implicit type conversions when the compared variables have different types.

This will set isTrueSet to a boolean true if the string is “true” and boolean false if it is string “false” or not set at all.


Don’t:

You should probably be cautious about using these two methods for your specific needs:

var myBool = Boolean("false");  // == true

var myBool = !!"false";  // == true

Any string which isn’t the empty string will evaluate to true by using them. Although they’re the cleanest methods I can think of concerning to boolean conversion, I think they’re not what you’re looking for.

8

  • 234

    myValue === 'true'; is precisely equivalent to myValue == 'true';. There is no benefit in using === over == here.

    – Tim Down

    Aug 26, 2010 at 11:01


  • 695

    I follow Crockford’s advice and use === and !== whenever it makes sense, which is almost always.

    – guinaps

    Feb 10, 2011 at 15:37

  • @guinaps most of the javascript strict conventions to blanket apply to all javascript usage just cause convoluted code and a lack of understanding of the principles, theory, or usage of javascript.

    – June

    Dec 7, 2021 at 18:35

  • 2

    === should be used because it’s also checking for the right type. Also, it has better comparison performances than ==.

    – NoxFly

    Dec 18, 2021 at 11:20

  • 1

    Thanks. Comes in handy when the value comes from an environment variable, which are strings JavaScript, and need to translate those into booleans.

    Apr 12 at 3:29

804

Warning

This highly upvoted legacy answer is technically correct but only covers a very specific scenario, when your string value is EXACTLY "true" or "false".

An invalid json string passed into these functions below WILL throw an exception.


Original answer:

How about?

JSON.parse("True".toLowerCase());

or with jQuery

$.parseJSON("TRUE".toLowerCase());

4

  • 78

    The problem with this is that many potential value generate a parse error which stops JS execution. So running JSON.parse(“FALSE”) bombs Javascript. The point of the question, I think, is not to simply solve these exact cases, but also be resilient to other cases.

    – BishopZ

    Jan 26, 2013 at 22:52

  • 53

    It’s pretty simple to just say JSON.parse("TRUE".toLowerCase()) so that it can parse correctly.

    – Yuck

    Aug 8, 2013 at 15:00

  • 1

    @BishopZ : Stopping JS execution is probably a desirable feature following best-pattern coding styles: en.wikipedia.org/wiki/Fail-fast

    – earizon

    Oct 13, 2021 at 10:04


  • If we go by question title alone it goes out of discussion all that JSON thing. The question was about a string not about what can result from its transformation. Of course looking at an object “stored” in a string using the JSON format one can ask what happens in such a scenario. Or we could go as well another way towards strings converted in numbers (not into objects) for example let x = 0 + "-0" // "0-0" versus let x = 0 - "-0" // 0 but, again, we move out of main topic 🙂

    – Eve

    Apr 30 at 13:03


282

const stringToBoolean = (stringValue) => {
    switch(stringValue?.toLowerCase()?.trim()){
        case "true": 
        case "yes": 
        case "1": 
          return true;

        case "false": 
        case "no": 
        case "0": 
        case null: 
        case undefined:
          return false;

        default: 
          return JSON.parse(stringValue);
    }
}

2

  • 53

    Actually it can be simplified. 1) There is no need to test for "true", "yes" and "1". 2) toLowerCase does not return null. 3) Boolean(string) is the same as string!=="" here. => switch(string.toLowerCase()) {case "false": case "no": case "0": case "": return false; default: return true;}

    – Robert

    Jun 25, 2013 at 5:27

  • 4

    Note, this will default to true – for example: stringToBoolean('banana') // true

    – dav_i

    Jul 7, 2021 at 13:25