JavaScript: Converting Strings to Booleans
Converting strings to booleans in JavaScript comes in handy when you’re dealing with user inputs or API responses that tend to arrive as strings but represent boolean values. This post covers how to do this.
Understanding the basics of converting strings to booleans
In JavaScript, every value falls into one of two categories: "truthy" or "falsy". This categorization is the cornerstone of converting strings to booleans. JavaScript defines the following values as falsy:
false
0
""
(an empty string)null
undefined
NaN
Conversely, JavaScript treats all other values, including non-empty strings, as truthy. This distinction is important for string to boolean conversion.
How to use the Boolean function for explicit conversion?
To explicitly convert a string to a boolean, use the Boolean
function. This method directly applies JavaScript's truthy and falsy rules, offering a clear path for conversion.
let trueString = "true"; let falseString = ""; let booleanTrue = Boolean(trueString); // true let booleanFalse = Boolean(falseString); // false
Leveraging logical operators for implicit conversion
Another way to convert a string to a boolean is by using logical operators, like !
(logical NOT). Double application, !!
, coerces a value to its boolean equivalent, reflecting JavaScript's interpretation of truthy and falsy values.
let trueString = "any non-empty string"; let falseString = ""; let booleanTrue = !!trueString; // true let booleanFalse = !!falseString; // false
Converting specific strings to booleans
If you want to convert specific strings like "true"
or "false"
to their boolean equivalents, you’ll need to craft a custom function. That’s because JavaScript doesn't automatically map these strings to boolean values.
function stringToBoolean(string) { switch(string.toLowerCase().trim()) { case "true": return true; case "false": return false; default: throw new Error("String does not represent a boolean value"); } } let trueBoolean = stringToBoolean("true"); // true let falseBoolean = stringToBoolean("false"); // false
Invite only
We're building the next generation of data visualization.
How to Remove Characters from a String in JavaScript
Jeremy Sarchet
How to Sort Strings in JavaScript
Max Musing
How to Remove Spaces from a String in JavaScript
Jeremy Sarchet
Detecting Prime Numbers in JavaScript
Robert Cooper
How to Parse Boolean Values in JavaScript
Max Musing
How to Remove a Substring from a String in JavaScript
Robert Cooper