How can I convert a string to boolean in JavaScript?

87

Solution 1

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.

Solution 2

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());

Solution 3

stringToBoolean: function(string){
    switch(string.toLowerCase().trim()){
        case "true": 
        case "yes": 
        case "1": 
          return true;

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

        default: 
          return Boolean(string);
    }
}

Solution 4

I think this is much universal:

if (String(a).toLowerCase() == "true") ...

It goes:

String(true) == "true"     //returns true
String(false) == "true"    //returns false
String("true") == "true"   //returns true
String("false") == "true"  //returns false

Solution 5

Remember to match case:

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

Also, if it's a form element checkbox, you can also detect if the checkbox is checked:

var isTrueSet = document.myForm.IS_TRUE.checked;

Assuming that if it is checked, it is "set" equal to true. This evaluates as true/false.

Share:
87
Imad
Author by

Imad

Updated on July 08, 2022

Comments

  • Imad
    Imad almost 2 years

    I know WPF. I want to start a small WPF App that will interact with database (SQL Server). I know how to develop it locally but I am worried about deployment. Client machine don't have .Net or SQL Server. Client OS may be Windows XP or Windows 7. What ORM should I use? How to add Database in my project? edmx, service-based databse?? or something other?

    • yurisich
      yurisich over 10 years
      Just to highlight an odd example of avoiding triple-equals comparison: I have a function currentSortDirection() that returns 1 for an ascending sort, 0 for a descending sort, and -1 for not set. Using while (currentSortDirection() != desiredSortDirection) { sortColumn() } works great, since -1 != true and -1 != false...but changing this to while (Boolean(currentSortDirection) !== ...) {...} forces -1 into a true, necessitating an additional couple of lines of prep, just to make jshint happy.
    • Rodrigo Siqueira
      Rodrigo Siqueira over 10 years
      Possible duplicate of stackoverflow.com/questions/263965
    • Nope
      Nope about 10 years
      @Droogans: What happens if desiredSortDirection is set to asc? I know in a controlled environment you are probably in control over the value desiredSortDirection is set to but in a shared environment when the input of desiredSortDirection can come from anywhere in any form, type-checking against custom objects and defensive programming can save a lot of hours of debugging. Your code is absolutely fine and nothing is wrong with it, I'm merely pointing out that there is no one-fit-all answer/solution and it will always be scenario dependant.
    • Mark K Cowan
      Mark K Cowan about 9 years
      "Is there a better way to accomplish this?" - there is certainly a worse way :D string=(string==String(string?true:false))?(string?true:fals‌​e):(!string?true:fa‌‌​​lse);
    • Leastrio
      Leastrio over 8 years
      Easily handle strings and bools: function parseBool(val) { return val === true || val === "true" }
    • Ranadheer Reddy
      Ranadheer Reddy almost 8 years
      article with good explanation coding-issues.com/2015/11/…
    • Sebi
      Sebi over 7 years
      @Mark function checkBool(x) { if(x) {return true;} else {return false;} }
    • Mark K Cowan
      Mark K Cowan over 7 years
      @Sebi: You forgot to document it: if (checkBool(x) != false) { ... } else { ... }
    • iamandrewluca
      iamandrewluca about 7 years
      !!(parseInt(value) || value === "true")
    • vitaly-t
      vitaly-t over 4 years
      You can't, it is impossible!
    • Agnius Vasiliauskas
      Agnius Vasiliauskas over 4 years
      Just a note. I am always amazed by Javascript expression parsing rule-set, for example, 123+44+'2'+1 gives "16721". Every + after '2' is interpreted as concatenation operation, wow :-D. While PHP gives 170 as an answer, which is more transparent, because in PHP plus is not ambiguous - it is just used for arithmetic operations. Concatenation operation is performed with different operator
    • Milos Radojevic
      Milos Radojevic over 4 years
      I haven't found an answer which solves undefined+string combination properly. So eventually I wrote one-liner for this: const StrToBool = (value) => !!value && value !== "false" && parseInt(value) !== 0; This one liner gives following results: StrToBool(undefined) => false, StrToBool('true') => true, StrToBool('false') => false, StrToBool('0') => false, StrToBool('Whatever') => true, StrToBool('1') => true
    • Admin
      Admin almost 4 years
      Why would you want to?
    • Firzok Nadeem
      Firzok Nadeem almost 4 years
      For these types of conversions, a good solution is to use a site like converttypes.com where you can see all conversions for almost all programming languages.
    • ZenAtWork
      ZenAtWork almost 4 years
      !myVar.slice(4,5); myVar = 'TRUE' // true myVar = 'FALSE' // false
    • danbars
      danbars over 3 years
      @AndrewLuca 's answer is great - it handles undefined, null and all other types. It considers non-zero numbers as true as well as the string 'true'. And all in a concise way.
    • varun sharma
      varun sharma about 3 years
      toBool ={'false':false,'true':true } invertBool = {'false':true,'true':false} can be used toBool[string]
    • Deepak paramesh
      Deepak paramesh almost 3 years
      JSON.parse('true') is the most easiest way to convert to boolean
  • Thomas Eding
    Thomas Eding over 14 years
    -1: Please don't advocate the use of eval (except perhaps for clever hacks and necessity).
  • moo
    moo over 14 years
    that's a really bad and insecure use of eval. and it's not even clever. -1
  • Mariano Desanze
    Mariano Desanze almost 14 years
    Why you think it would be silly to use ===? In terms of performance it would be exactly the same if both types are Strings. Anyway, I rather use === since I always avoid the use of == and !=. Justifications: stackoverflow.com/questions/359494/…
  • Tim Down
    Tim Down over 13 years
    myValue === 'true'; is precisely equivalent to myValue == 'true';. There is no benefit in using === over == here.
  • guinaps
    guinaps over 13 years
    I follow Crockford's advice and use === and !== whenever it makes sense, which is almost always.
  • tillda
    tillda about 13 years
    You can use true.toString() instead of "true" to be even more clean :-)
  • Shadow2531
    Shadow2531 almost 13 years
    You can always prefix the function if you're afraid that it'll interfere with some other code. If some code still breaks, that code is just too brittle and should be fixed. If your added function makes the object too heavy where it cause a performance issue for other code, then, obviously you don't want to do that. But, I don't think it's generally a bad idea to extend built-in objects. They also wouldn't be publicly extendable if that was the case.
  • Szymon Wygnański
    Szymon Wygnański almost 13 years
    Modifying the prototype is very bad idea
  • devios1
    devios1 over 12 years
    @DTrejo @Szymon I disagree. This is exactly the kind of thing overloading the prototype is for. If you're afraid of it breaking (poor) code that relies on for..in, there are ways to hide properties from enumeration. See Object.defineProperty.
  • pauloya
    pauloya about 12 years
    When you can receive a string in uppercase or a boolean, then String(a).toLowerCase() === 'true'
  • YMMD
    YMMD about 12 years
    What conversion were you talking about? :-)
  • GrahamMc
    GrahamMc over 11 years
    To understand what's "wrong" (or right) with eval - check out articles like javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval or search on stackoverflow for 'Javascript eval malware'
  • cypher
    cypher over 11 years
    @SzymonWygnański: i disagree. I do not see any other reason apart from for--in loop and native support for the same functionality by browsers. Reg for-inloop: i cannot think of a case, where for-in loops are really needed in string. Reg native support: we can definitely add a proto prop until native browsers support, if we are not building a framework like - prototype or jquery, etc... More about this by @Kangax(Perfection kills) is here. webcache.googleusercontent.com/…
  • ars265
    ars265 over 11 years
    When comparing string in javascript there is no difference between using the == or === operators when not using conversions. Here you are comparing to strings, therefore no type conversions. See stackoverflow.com/questions/359494/…
  • Szymon Wygnański
    Szymon Wygnański over 11 years
    Consider: we can go even farther: "true".checkbox() would convert to checkbox, or "true".application() would convert to app:D Not only for-in loops fail but the style is wrong here. Where would you look for the code of this "boolean/checkbox/application" definition in a big app? Imagine world where every library would do thinks like that. Isn't it much better to define a class or function: checkbox("true") - it's just cleaner and almost the same amount of letters. You never know IF browsers will support your custom function until it's defined as a standard (like Object.create etc...).
  • BishopZ
    BishopZ over 11 years
    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.
  • thdoan
    thdoan over 11 years
    I agree that var isTrueSet = (myValue === 'true'); is the best answer.
  • JMTyler
    JMTyler about 11 years
    Just to go back to your objectives, the only problem with your third & best solution is that it does not meet Objective #1 - it will only return true for a value of 'true', but not for any truthy input. In order to make it meet Objective #1, it is only slightly more concise than Solution #2, and far less readable.
  • Robert
    Robert almost 11 years
    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
    Robert almost 11 years
    Since value will always be a string neither == nor === are silly. Both are the right tool for this job. They only differ when the types are not equal. In that case === simply returns false while == executes an intricate type coercion algorithm before comparison.
  • Yuck
    Yuck almost 11 years
    It's pretty simple to just say JSON.parse("TRUE".toLowerCase()) so that it can parse correctly.
  • Etienne
    Etienne almost 10 years
    The 'without JSON' version has some flaw: val="0" ; console.log(!!(+val||String(val).toLowerCase().replace(!!0,'‌​')) ); produces true
  • Ron Martinez
    Ron Martinez over 9 years
    getBool(undefined) will crash When using the original JSON version and will return true for the 2nd version. Here is a 3rd version which returns false: function getBool(val) { var num; return val != null && (!isNaN(num = +val) ? !!num : !!String(val).toLowerCase().replace(!!0,'')); }
  • Imad
    Imad over 9 years
    thanks for your reply. How can I bundle .Net Framework Installer and SQL Installer?
  • ViBi
    ViBi over 9 years
    In case you are creating the installer using Installshield, you can add pre-requisites in it.
  • Imad
    Imad over 9 years
    I dont want my client to install prerequisites seperately
  • jakubiszon
    jakubiszon over 9 years
    If you wanted it short why not writing just var isTrueSet = myValue === "true"; ?
  • whitfin
    whitfin over 9 years
    JSON.parse is able to handle parsing 'true' and 'false' to Boolean values, so you don't need to wrap it in Boolean().
  • MarceloBarbosa
    MarceloBarbosa over 9 years
    This is good, but works only with String type. Imagine that this need be used by a variable that is maybe "true" or true. If come the second one, this will not work. Is possible make a document.prototypeto use this wherever we want it?
  • cassi.lup
    cassi.lup about 9 years
    This looks elegant. Great job! However, I noticed that overloading basic prototypes in large JS apps (that also need unit testing) might result in some unexpected behaviour (namely, when you want to iterate with "for" through an array that has the prototype overloaded, you'll get some properties that you wouldn't normally expect). You have been warned. ;)
  • Pierre-Adrien
    Pierre-Adrien about 9 years
    For a string, I personnally would have returned true for "true" like you did, but false for "false" only, and undefined otherwise. Sort of what you previously made with the integer case.
  • null
    null about 9 years
    my bad i have fixed the above snippet - works now. not sure how those inverted commas "" got in there! ;/ @HugoZapata
  • Hugo Zapata
    Hugo Zapata about 9 years
    But the question is, how to convert a string to boolean. new Boolean("false") doesn't work, so your answer is not correct.
  • null
    null about 9 years
    @HugoZapata updated the answer, yes was incorrect (but strangely was working before) updated answer works correctly now.
  • foxdonut
    foxdonut almost 9 years
    What is the point of the if/else? You are alert'ing the same thing in both branches.
  • null
    null almost 9 years
    @foxdonut because if boolean == false, then you can do something different in the else statement - the alert is just an example. even though its the same it outputs something different if the boolean var = true/false.
  • Snowman
    Snowman almost 9 years
    I like that it's concise. But it fails spectacularly for the basic case of eval('TRUE'); proving once again, that eval() is evil.
  • thdoan
    thdoan almost 9 years
    @Area 51 Detective Fiction, in the same fashion, JSON.parse('TRUE') from the answer below also fails spectacularly. It's quite easy to force an error condition in JavaScript (or any language, for that matter). To account for this, you should normalize the string first, e.g., var myValue = document.myForm.IS_TRUE.value.toLowerCase(); var isTrueSet = (myValue==='true' || myValue==='false') ? eval(myValue) : false;
  • Snowman
    Snowman almost 9 years
    @10basetom: Quite correct. You should include .toLowerCase() in the answer is my point. I'm not trying to force anything. Uppercase TRUE is a common enough value to be returned by many UI widgets.
  • bortunac
    bortunac over 8 years
    a variant of yours that accepts boolean too function StringOrElse2Bool(sob){ if (typeof sob === "string") { return ["no", "false", "0", "off"].indexOf( sob.toLowerCase() ) !== -1 ? false : true; } else { return !!sob }
  • Kevin Boucher
    Kevin Boucher almost 8 years
    return /^(true|yes|1|t|y)$/i.test(str);
  • Oskar Berggren
    Oskar Berggren over 6 years
    So it would return true for "False", would it not?
  • spottedmahn
    spottedmahn over 6 years
    "something went wrong" when trying to view jsPerf test
  • Steel Brain
    Steel Brain over 5 years
    Don't change globals, try to keep your changes isolated, maybe create a new function parseBoolean instead
  • Zarepheth
    Zarepheth over 5 years
    As written (on 2018 Dec 19 at 16:00 Z), /^(false|0|no)*$/i will match an empty string (which may be the intent) but also matches any number false, 0, or no, for instance "0falseno0nofalse0" will also evaluate to false but should evaluate to null and output a console message that it is not a Boolean value.
  • Denis Nutiu
    Denis Nutiu about 5 years
    I'd rather not introduce a new dependency to the project just for converting a string to a boolean.
  • Ratan Uday Kumar
    Ratan Uday Kumar about 5 years
    It is very light weight and also u can validate whether string is boolean
  • serdar.sanri
    serdar.sanri about 5 years
    wouldn't return str.toLowerCase() === 'true' simpler?
  • Dayem Siddiqui
    Dayem Siddiqui about 5 years
    Ah! you are 100% correct :) . Wrote that answer a few years ago. A better ES6 way of achieving the same result would be: const strToBool = (str) => str.toLowerCase() === 'true'
  • zeross
    zeross almost 5 years
    Ternary operator is not necesary. Only with let output = value === 'true' works.
  • panatoni
    panatoni almost 5 years
    let value = 'true'; let output = value === 'true' ? true : false; output = true; let value = 'false'; let output = value === 'true' ? true : false; output = false; What is not working here?
  • zeross
    zeross almost 5 years
    Sorry, it has been a missunderstanding. That works perfectly, but it's redundant. value === 'true' already returns a boolean value and ternary operator is not necesary.
  • panatoni
    panatoni almost 5 years
    Yeah sure you are right, I edited my answered - my fault ;]
  • James Wilkins
    James Wilkins over 4 years
    Or true.toString()==='true'. Also, why are you making String(true) and String('true') lowercase? lol
  • thisismydesign
    thisismydesign about 4 years
    Boolean("false") => true
  • Patrick Matte
    Patrick Matte about 4 years
    Here's mine function boolify(value = false) { return ["true", "1", "yes", "y", "on"].indexOf(String(value).toLowerCase()) != -1; }
  • Justin Liu
    Justin Liu almost 4 years
    @OskarBerggren It wouldn't. Look at the code, if (bool === 'false') bool = false then, when it runs return !!bool it's returning !!false which is false.
  • Oskar Berggren
    Oskar Berggren almost 4 years
    @JustinLiu jsfiddle certainly evaluates toBoolean('False') to true which I think is probably not a good idea. With respect to the actual question, which was about a string representing a boolean value, I frankly think it's a bad idea to return true for "any "other" "random" "string" - it should raise an error instead of assuming that a caller that sent an erroneous string is happy with having that interpreted as true.
  • Angelo Oparah
    Angelo Oparah almost 4 years
    not to mention that .toLowerCase might throw if myValue is equal to null or undefined
  • D. Pardal
    D. Pardal almost 4 years
    There are so many more performant and safer ways to do this.
  • D. Pardal
    D. Pardal almost 4 years
    Not guaranteed to return a boolean, though.
  • kabirbaidhya
    kabirbaidhya over 3 years
    It should be noted that using eval for trivial cases like this is NOT RECOMMENDED. Read this developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • kabirbaidhya
    kabirbaidhya over 3 years
    This isn't a recommended solution. Read more - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • Vaibhav S
    Vaibhav S over 3 years
    Boolean("false") === true // output true
  • Vaibhav S
    Vaibhav S over 3 years
    simplified version: storeBooleanHere = stringVariable.toLowerCase() !== 'false' ;
  • Dan
    Dan over 3 years
    For such a simple task, a library would not be desirable especially when the library controls how a boolean is defined.
  • Shubham Chaudhary
    Shubham Chaudhary over 3 years
    Quoting mozzila docs: Warning: Executing JavaScript from a string is an enormous security risk. It is far too easy for a bad actor to run arbitrary code when you use eval(). developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…!
  • Khanakia
    Khanakia over 3 years
    What do we say this type of function ?
  • Wyck
    Wyck over 3 years
    Downvoted because you posted an image of the code rather than the code itself.
  • Jonathan Lyon
    Jonathan Lyon over 3 years
    this is so awesome and useful - thank you so much!
  • Prashanth Hegde
    Prashanth Hegde about 3 years
    Any specific reason for using !!v instead of using true directly?
  • jbalintac
    jbalintac about 3 years
    Isn't Boolean("false") returns true
  • ksugiarto
    ksugiarto almost 3 years
    How about '1'? Should it be converted to true or false? I think it is should be true, no? But using your answer, it will returns false
  • Felipe Chernicharo
    Felipe Chernicharo almost 3 years
    Guess you are doing something wrong bro... I just tested the code and if you input ' 1 ' the return is always true. Don't know how you got that false but I think you must be messing it up in some way
  • ksugiarto
    ksugiarto almost 3 years
    Ah sorry! My bad, I was testing the first function instead. Thanks for clarifying this.
  • Akin Zeman
    Akin Zeman almost 3 years
    same as y= (x=='true');
  • dav_i
    dav_i almost 3 years
    Note, this will default to true - for example: stringToBoolean('banana') // true
  • Alexander Santos
    Alexander Santos almost 3 years
    This sounds too specific. Mind explaining it?
  • Kieran Ryan
    Kieran Ryan almost 3 years
    @Wyck you failed to mention that presentation is nice.
  • Asinus Rex
    Asinus Rex almost 3 years
    This works, but you have to be careful not to pass it empty strings or it'll pop.
  • Richard Torcato
    Richard Torcato over 2 years
    Boolean.prototype is fully supported in all browsers
  • earizon
    earizon over 2 years
    @BishopZ : Stopping JS execution is probably a desirable feature following best-pattern coding styles: en.wikipedia.org/wiki/Fail-fast
  • earizon
    earizon over 2 years
    if(str == null) return false; will return random errors each time an input is wrongly initialized to null. Being tolerant is not a desirable feature most of the times:
  • Muhammed Moussa
    Muhammed Moussa over 2 years
    the sexy solution, I liked it!
  • Woozar
    Woozar over 2 years
    This will fail if myValue is null or undefined or any type other than a string.
  • June
    June over 2 years
    @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.
  • NoxFly
    NoxFly over 2 years
    === should be used because it's also checking for the right type. Also, it has better comparison performances than ==.
  • prabhatojha
    prabhatojha over 2 years
    hmm, this is perfect
  • opticyclic
    opticyclic over 2 years
    Pass "True" to this and it returns false
  • ru4ert
    ru4ert over 2 years
    @opticyclic ok, i minded this and created a fix.
  • stu0292
    stu0292 over 2 years
    I'm using this approach for a framework that parses URL parameters and includes parameters without values as an empty string, something like: example.com?useSpecialFeature ends up as {useSpecialFeature:''}
  • Max Waterman
    Max Waterman over 2 years
    This doesn't account for 'false'...if the string isn't 'true' or 'false', then myBool should probably be undefined. eg let myBool = (myValue === 'true')?true:(myValue === 'false')?false:undefined;
  • royce3
    royce3 over 2 years
    yours was almost what I was looking for. Here's my variation: ``` function parseBool( value, nullOnFailure = false ) { let value2 = parseFloat( value ) if( !isNaN( value2 )) return !!value2 if( typeof value !== 'string' ) return !!value switch( value.trim().toLowerCase() ) { case 't': case 'true': case 'on': case 'y': case 'yes': return true case 'f': case 'false': case 'off': case 'n': case 'no': return false default: return nullOnFailure ? null : false } } ```
  • hargobind
    hargobind about 2 years
    I love the simplicity of the regex approach to check for values that are typically "true". A suggestion for modification: the logic of false is 0 and true is non-zero. Therefore I think it's better to check for the opposite of false, i.e. return !(/^(false|0|off|no)$/i).test(this); -- also notice that I included "no".
  • Just a coder
    Just a coder about 2 years
    take all my money! 💵
  • Iglesias Leonardo
    Iglesias Leonardo about 2 years
    I would instead use true as 1 and false as 0. It would allow you to use methods like parseInt() and compare it's value using if(parseInt(booleanVariable))
  • Jose Quijada
    Jose Quijada about 2 years
    Thanks. Comes in handy when the value comes from an environment variable, which are strings JavaScript, and need to translate those into booleans.
  • marko-36
    marko-36 about 2 years
    This is a quick and dirty solution for storing true/false inside .env
  • Ivan Yulin
    Ivan Yulin about 2 years
    should wrap in try/catch in many cases
  • Eve
    Eve about 2 years
    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 :)
  • Elijah Lynn
    Elijah Lynn almost 2 years
    This does account for false as if the string doesn't match or is undefined then the conditional will evaluate to boolean false. I updated the answer.