The easiest way to convert a string to a boolean is to compare the string with ‘true‘ in JavaScript. Use toLowerCase()
to convert a given string in lowercase to better compare a string.
let myBool = (myString === 'true');
// OR
let myBool = (myString.toLowerCase() === 'true');
Note: toLowerCase()
will throw an error if myString
is null
or undefined
.
Using the identity operator (===
), which doesn’t make any implicit type conversions when the compared variables have different types.
JavaScript string to boolean
Simple example code converting string “true” / “false” to a boolean value.
<!DOCTYPE html>
<html>
<body>
<script>
let s1 = 'true';
let res1 = (s1.toLowerCase() === 'true');
console.log(res1);
let s2 = 'False';
res2 = (s2.toLowerCase() === 'true');
console.log(res2);
let s3 = 'Test';
res3 = (s3.toLowerCase() === 'true');
console.log(res3);
</script>
</body>
</html>
Output:
To improve performance, and in real-world cases where form inputs might be passing values like ‘true’, or ‘false’, this method will produce the best results.
function stringToBool(val) {
return (val + '').toLowerCase() === 'true';
}
One liner with a ternary if.
var bool_value = value == "true" ? true : false
You can convert a string to a boolean value using various techniques. Here are a few common methods:
Boolean() function: The Boolean()
function in JavaScript can be used to convert any value to a boolean. When you pass a string to Boolean()
, it returns true
for non-empty strings and false
for empty strings.
var str = "true";
var boolValue = Boolean(str); // true
Using comparison: You can compare the string with another string or an empty string to coerce it into a boolean value.
var str = "false";
var boolValue = (str === "true"); // false
Ternary operator: You can use a ternary operator for a more concise way of achieving the same result.
var str = "true";
var boolValue = (str === "true") ? true : false; // true
Strict equality: This is similar to the comparison method, but using strict equality (===
) ensures that the type and value are both the same.
var str = "false";
var boolValue = (str === "true"); // false
JSON.parse(): If your string represents a JSON boolean value ("true"
or "false"
), you can use JSON.parse()
.
var str = "true";
var boolValue = JSON.parse(str); // true
Do comment if you have any doubts or suggestions on this JS boolean topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version