- How to convert a string to a boolean (the right way)
- 1) You might be tempted to say if(myString)…
- 2) What about creating a boolean object from the string?
- 3) Right, let’s try comparing our string against the string “true”
- 15 thoughts on “How to convert a string to a boolean (the right way)”
- Convert String to Boolean in JavaScript
- Using Identity Operator (===)
- Using Regular Expressions (RegEx)
- Using the Boolean Wrapper Class?
- Free eBook: Git Essentials
- Double NOT Operator — !!
- Conclusion
How to convert a string to a boolean (the right way)
There are a couple of ways to convert a string variable to a boolean variable in Javascript. However, when doing this, you have to be kind of careful: it’s kind of easy to mess up this sort of logic and doing it wrong can result in some nasty bugs. So, in order to save you a headache or two, I’ve detailed how to do it properly in this article. Read on, if you’re interested.
1) You might be tempted to say if(myString)…
…and this would appear to work, for a while. However, it’s really the wrong way to go about this. Observe:
var myString = true; if (myString) < // this should evaluate to true because myString = "true", and it does. Good! >if (!myString) < // uh oh! This evaluates to true as well. Why? Because if(!myString) // is checking to see if myString *exists*, not if it's *true*. >
As I mentioned, if(!myString) evaluates to true because that statement only checks if myString exists (e.g. if it’s not undefined or null), not if it evaluates to false.
2) What about creating a boolean object from the string?
Why not try to create a Boolean object from the string? Well, you’d run into an issue similar to the previous problem. Let’s let some example code do the talking, though, have a look:
var myString = "true"; if(Boolean(myString)) < // very good, this if statement evaluates to true correctly! >if(!Boolean(myString)) < // and this one evaluates to false! Our problems are solved! >var myOtherString = "false"; if(Boolean(myOtherString)) < // . or are they? This evaluates to true, although we clearly set it to "false"! >
As you can see, if(Boolean(“false”)) evaluates to true–why? When you create a new Boolean object from a string, it doesn’t try to check whether the string equals “true” or “false”. Instead, rather misleadingly, it checks whether the variable is a non-falsy value (e.g. a value that evalutes to false–0, undefined, an empty string, null, etc). Because myString is not an empty string, the Boolean evaluates to true–even if myString equals false.
3) Right, let’s try comparing our string against the string “true”
Really, the correct way we should be going about this is to check if our string equals “true” — if so, then our string is obviously “true”. Otherwise, it must be false. We can do it this way:
var myString = "true"; if(myString == "true") < // this evaluates to true correctly, myString is true >if(myString == "false") < // this evaluates to false, also correct, since myString doesn't equal false. >
Wonderful, it looks like our problem is solved! But, you know something? The above code is kind of messy and a bit long just to check if our string is “true” or not. Let’s see if we can’t clean it up a bit:
Ahh, nice and clean. Just the way I like it! (note: the parentheses are just there for clarity–if you don’t like them or you’re extra extra concerned about line length, removing them won’t cause any errors).
15 thoughts on “How to convert a string to a boolean (the right way)”
Why not remove a few of those non-string case conditions by just saying “value = value.toString()” on the first line of the function?
do you see value in casting myString to lower so it is a little more robust?myString = (myString.toLowerCase() == “true”);
Well, yes, that’s technically an improvement, although very slight. Realistically, though, it’s not worth the time you spend typing it. Plus, it encourages typing “True” instead of “true”, which could become a source of confusion.
nice and clear
Wow, that’s a nice script, thanks. But why the date of this post is “November 30, -0001”?
Something is wrong with your implementation. You say:
var myString=”true”;
myString=(myString==”true”);
would be evaluated right, no matter what, but how does this work when I initialize myString=true . It won’t! The right implementation that would work no matter if you initialize your variable with the Boolean true|false or with the String true|false would be: var myString=X; // where X could be any “true”|”false”|true|false
myString=String(myString)==’true’
will always evaluate right. Right?
var myString = “true”;
if (!myString) // uh oh! This evaluates to true as well. Why?
That’s wrong. !’true’ evaluates to FALSE because the string ‘true’ exists. The correct example sholud be: !’false’ !’false’ evalutes to FALSE, because it evaluates if the string ‘false’ exists and negates the value
There is an error in the first example var myString = true;
if (!myString) // This evaluates to false.
>
Normally I would just ignore this post but it is well ranked on Google for me so I will post a correction for the sake of others who come here. This makes absolutely no sense and your code will confuse the hell out of anybody who needs to maintain it (including probably yourself). Just to illustrate what is wrong here, javascript has a very simple set of rules to define how variables are cast when doing loose equality checking (==) [1]. This method disobeys the language’s standard rules: function isTruthy (inp) <
var bool = (inp == “true”);
return bool;
>
// returns true. wierd, but OK…
isTruthy(“true”);
// returns false. WTF?
isTruthy(“1”);
// javascript is a loosely typed language, so this
// should work, but does not:
isTruthy(true);
// stupid corner case, but for demonstration
var obj = <>;
obj.toString = function () < return ‘true’;>
castToBool(obj); // returns true What you are actually looking for here is strict equality checking [2]. You are overriding the language’s behavior with your own string-based logic. You are not casting to bool, you are trying to see if a given variable is exactly the string “true”. This is fine (in fact, lots of JS gurus say you should never use the loose checking operator), but you need to be explicit about it. This is much simpler and easier to understand: myString === “true” [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Loose_equality_using [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness#Strict_equality_using
Nice. Easy way to convert string to boolean is by checking manually using if condition. Following post explains about it
http://www.coding-issues.com/2015/11/convert-string-to-boolean-in-javascript.html
Cool, thanks for this info. I was wondering why it wasn’t working, but this makes perfect sense. Thanks again and good luck.
Convert String to Boolean in JavaScript
Suppose we have boolean values stored in our database as strings and based on those values we want to perform some specific operation on our website/application. In that case, we have to convert those strings into boolean values before using them in logical operations.
In this article, we’ll take a look at several ways of converting string values to boolean ( true or false ) in JavaScript.
Using Identity Operator (===)
The identity operator, also known as a strict equality operator, returns true only if and only if both values being compared are of the same type and have the same value. In other words, it determines whether the value on the left-hand side is equal to the value on the right-hand side — and returns true if they are, and false if they are not.
Note: If you want to learn more about the difference between == (strict equality operator) and === (loose equality operator), you should read our «JavaScript: == vs === Operator»!
Essentially, we’ll compare our string to the string «true» . Therefore the output will be a boolean true only if our string is actually «true» . Any other string will cause the code to return the false boolean value:
let myString = "true"; let boolOutput = (myString === "true"); //returns true
Note: We write a string value with quotes — «true» , and the boolean value without quotes — true . We’ll use this notation throughout this whole article.
Additionally, we can convert a string to lowercase first, just to make sure the letter case won’t cause any faulty outputs:
let myString = "True"; let boolOutput = (myString.toLowerCase() === "true"); // returns true
As we’ve stated before, the previous code will return false if our string value is not equal to «true» :
let myString1 = "Test"; let boolOutput1 = (myString1 === "true"); //returns false let myString1 = "Test"; let boolOutput1 = (myString1.toLowerCase() === "true"); //returns false let myString = "True"; let boolOutput2 = (myString2 === "true"); //returns false
We can also spice things up a little by introducing the ternary operator alongside the equality operator. All we will do is check if our string is equal to «true» and then return either a boolean value of true if there is a match or false if it doesn’t:
let myString = "true"; let boolOutput = myString.toLowerCase() == 'true' ? true : false; // returns true
Using Regular Expressions (RegEx)
Regular expressions (RegEx) are patterns for matching and testing string character combinations.
Note: In this article, we’ll assume you have at least a basic understanding of regular expressions in general. But if you need help to get a grasp on regular expressions in JavaScript, you should consider reading our «Guide to Regular Expressions and Matching Strings in JavaScript»
For the purpose of this article, we’ll use the most basic form of regular expressions in JavaScript — we’ll create the simple regex that matches «true» and match it against our string using the test() method:
let stringValue = "true"; let boolValue = (/true/).test(stringValue); //returns true
You will notice this is actually case-sensitive, as this will return false if it has slight case inconsistency:
let stringValue = "True"; let boolValue = (/true/).test(stringValue); //returns false
To fix this, we can add /i at the end of the regular expression to ensure for case-insensitive match:
let stringValue = "True"; let boolValue = (/true/i).test(stringValue); //returns true
Using the Boolean Wrapper Class?
JavaScript has a built-in Boolean object for storing boolean values. It is actually an object wrapper for boolean values — it wraps around other objects thus making them a valid boolean value. This is done by testing the truthy-falsy value of an object. In general — empty objects are evaluated to false , and non-empty objects are evaluated to true .
Any string which isn’t the empty string will evaluate to true by using the Boolean wrapper:
let myString1 = Boolean('true'); //returns true let myString2 = Boolean(''); // //returns false let myString3 = Boolean('false'); //returns true let myString4 = Boolean('True'); //returns true
There are two major issues here:
- The first is that this will return true for an empty string with at least one blank character (space, tab, etc.), that is why we have to be cautious when using this method:
const myString5 = Boolean(' '); //returns true
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
- Secondly, converting a string of «false» to a boolean value of false will fail because any non-empty string converts to true .
Double NOT Operator — !!
Using the double NOT operator is equal to using the logical NOT operator ( ! ) twice, which means that it inverts the result of the single NOT operator:
let myString1 = !'test'; // returns false let myString2 = !''; // returns true
When we use the double NOT operator, the values are flipped, meaning we are now performing a pure boolean conversion:
let myString1 = !!'test'; // returns true let myString2 = !!''; // returns false
The double NOT ( !! ) operator is quite concise but does the same thing as the Boolean wrapper. However, it’s a bit harder to read if you’re not familiar with the logical NOT ( ! ) operator.
We also have to be cautious when using this method as an empty string with at least one blank character will still return true and when we try to convert a string of «false» to a boolean value of false , this will still not work (just as with Boolean object).
Conclusion
In this article, we’ve taken a look at four ways to convert a string into a boolean in JavaScript. The simplest way to do so is to use the strict equality operator to compare our string value to the «true» — if the string is (strictly) equal to «true» , the output will be boolean true . Alternatively, you can use the ternary operator alongside the loose equality operator to achieve the same. Also, regular expression matching is a solid approach.
The last two methods, Boolean object and double NOT operator, have a simpler syntax, but their drawback is the way they treat the false value — string «false» will return the boolean value true , which makes them applicable only to a small subset of conversion cases.