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.
Basic Example
var str='true';
var isBoolean= (str === 'true');
console.log(typeof isBoolean);
When working with HTML elements, few elements only deal with boolean type values, and you may have string data to process.
This tutorial teaches you the different methods to convert a string to a boolean in JavaScript and when it is appropriate to use them.
Table of Contents
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);
This method is case-sensitive. In this approach, you will be doing an exact match of string comparison.
Output
Value of isBoolean: true
Type of isBoolean: boolean
The string variable(str)
is compared against the string value true
, and it returns true
if it matches exactly.
Code
Now let us see another example. Here the variable str holds value True.
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
To compare in a case-insensitive way,
- Convert the
string
value to equivalent javascript letter casing before comparing it with a conditionalstring
value.
Code
var str='True';
var isBoolean= (str.toLowerCase() === 'true');
console.log("Value of isBoolean: "+ isBoolean);
console.log("Type of isBoolean: "+ typeof isBoolean);
Output
The output will be true
because both the strings are in the same case.
Value of isBoolean: true
Type of isBoolean: boolean
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,
- Pass the
string
value to the Boolean constructor, - 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 the boolean and inverse it. Anything will be false now, So to reverse the value to true, 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
- 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 values 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 a 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.
This is wonderful and great learning
Thank you for your support and feedback