How to Convert String to Boolean in JavaScript

Here are four ways to convert a string to a boolean in JavaScript:

  1. Using identity operator(===)
  2. Using regex
  3. Using Double NOT (!!) operator
  4. Using Boolean wrapper

Method 1: Using the identity operator(===)

The identity operator (===) in JavaScript is used for strict equality comparison, meaning it checks both value and type and you can use it for conversion.

const str = 'true';
const boolValue = str === 'true';

console.log(boolValue)
console.log(typeof(boolValue))

Output

true
boolean

Method 2: Using regex

To parse a string to a boolean using regular expressions (regex), you need to check if the string matches certain patterns that represent “true” or “false”.

function stringToBoolean(str) {
  // Matches 'true', 'yes', or '1' (case-insensitive)
  const truePattern = /^(true|yes|1)$/i;
  
  // Returns true if it matches, false otherwise
  return truePattern.test(str.trim());
}

const testString1 = "true";
console.log(stringToBoolean(testString1));

const testString2 = "yes";
console.log(stringToBoolean(testString2));

const testString3 = "no";
console.log(stringToBoolean(testString3));

Output

true
true
false

You can adjust the truePattern regex to include or exclude other string representations of true or false as per your requirements.

Method 3: Using the Double NOT operator(!!)

In JavaScript, the double NOT operator (!!) is a common approach to convert a value to its boolean representation based on its truthiness or falsiness.

  1. The first ! negates the value, converting it to a boolean and inverting it.
  2. The second ! negates it again, bringing it back to its original truthiness or falseness but now as a boolean type.
console.log(!!"");
console.log(!!"hello");
console.log(!!"false");
console.log(!!"0");

Output

false
true
true
true

Method 4: Using Boolean Wrapper

JavaScript Boolean object represents a boolean value. This method works just like the double NOT operator, and it will convert a string to a boolean value.

let data = "Millie Bobby Brown"

let data_bool = Boolean(data)

console.log(typeof(data_bool))
console.log(data_bool)

Output

boolean
true

Choose the method that best suits your application’s requirements.

If you need a reliable and error-safe method, going with “JSON.parse() or a custom function would be advisable.”