Let’s look at some ways to convert a string to a boolean in JavaScript.
1. Compare String with true
To convert a string to a boolean, we can use the strict equality operator to compare the string with the true
string. For example:
const str1 = 'true';
const str2 = 'false';
const bool1 = str1 === 'true';
const bool2 = str2 === 'true';
console.log(bool1); // true
console.log(bool2); // false
Note: Use toLowerCase()
to ignore the casing of the string before the conversion:
const str1 = 'TRUE';
const bool1 = str1.toLowerCase() === 'true';
console.log(bool1); // true
Note: Using the Boolean
constructor to convert the string will result in true
if the string is not falsy. Empty strings are the only falsy strings. All other strings are truthy.
const str1 = 'true';
const str2 = 'false';
const str3 = '';
const str4 = 'a';
const bool1 = Boolean(str1);
const bool2 = Boolean(str2);
const bool3 = Boolean(str3);
const bool4 = Boolean(str4);
console.log(bool1); // true
console.log(bool2); // true
console.log(bool3); // false
console.log(bool4); // true
2. JSON.parse()
We can also convert a string to a boolean in JavaScript with the JSON.parse()
method. For example:
const str1 = 'true';
const str2 = 'false';
const bool1 = JSON.parse(str1);
const bool2 = JSON.parse(str2);
console.log(bool1); // true
console.log(bool2); // false
Note: Attempting to parse the true
or false
string, when it is not all lowercase, will cause an error:
const str1 = 'TRUe';
const bool1 = JSON.parse(str1); // throws SyntaxError
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.