Why Are You Converting Strings to Booleans?
Really, you should not be storing boolean data in a string, but there are several scenarios where it can arise:
- Boolean values arising from user input
- Values taken from HTML form elements, which can only contain string values
- Data taken from poorly formatted third party sources, like APIs or CSV files
Once you have data containing boolean values as strings, you must determine what form those strings take, and what will be considered a TRUE value.
There is no real need for a re-usable function for this task – converting from a string value to a boolean value is simply the result of a single comparison.
In the below example, the expected value for a TRUE value in a string is “true” – the string value to convert is compared to this expected value, and a boolean value is returned based on whether it is a match:
var stringValue = "true"; var booleanValue = (stringValue === "true"); // Results in a boolean value of TRUE as it is a match for "true" var stringValue = "false"; var booleanValue = (stringValue === "true"); // Results in a boolean value of FALSE as it is not a match for "true"
Similarly, if you are expecting a “1” for the value of true (and a “0” for false), as some boolean values as stored numerically and may have been converted to strings:
var stringValue = "1"; var booleanValue = (stringValue === "1"); // Results in a boolean value of TRUE as it is a match for "1" var stringValue = "0"; var booleanValue = (stringValue === "1"); // Results in a boolean value of FALSE as it is not a match for "1"
You must use the strict equality === operator to ensure both the value of the variable and the type are the same when making the comparison – otherwise loose comparisons may result in unexpected behaviour.
Keep Your Types in Order