We can use JavaScript to convert a string variable to a boolean value by using the JavaScript Boolean() function. Non-empty strings are converted to true and empty strings are converted to false.
var some_string = "This is a string";
var empty_string = "";
console.log(Boolean(some_string));
console.log(Boolean(empty_string));
#Output:
true
false
If you just want to check if a string is equal to “true”, then you can perform a check with the equality operator ===.
var some_string = "true";
console.log(some_string === "true");
#Output:
true
When working with different variable types in JavaScript, the ability to convert variables to other variable types easily is valuable.
One such case is if you want to convert a string to a boolean value.
To convert a string variable to a boolean value in JavaScript, you can use the JavaScript Boolean() function.
Non-empty strings are converted to true and empty strings are converted to false.
Below shows you a simple example of how you can convert strings to boolean values with Boolean() in JavaScript.
var string1 = "true";
var string2 = "false";
var string3 = " hello";
var string4 = "";
console.log(Boolean(string1));
console.log(Boolean(string2));
console.log(Boolean(string3));
console.log(Boolean(string4));
#Output:
true
true
true
false
Checking if a String is Equal to true in JavaScript
If you just want to check if a string is equal to “true”, then you can perform a check with the equality operator ===.
This can be the case if you have user input and want to see if the user input “true” or “false”.
As we know from above, a string with value “false” will resolve to true when converted to a boolean value.
Therefore, we just need to do a simple check to verify the value of the string variable.
Below is a simple example showing you how to check if a string is equal to “true” in JavaScript.
var some_string = "true";
console.log(some_string === "true");
#Output:
true
Hopefully this article has been useful for you to learn how to use JavaScript to convert string to bool.