Register Login

Convert String to Boolean in JavaScript

Updated Sep 18, 2023

Converting strings into Boolean values to perform certain operations have several use cases in different domains. For instance, let us create a database having Boolean values in string data type.

But if users want to perform certain Boolean operations like conditional operations or return 0 or 1, they need to convert the string values into Boolean values first to achieve so. These strings contain "true" or "false." Users need to convert these strings to Boolean to execute the actions.

This article provides all the relevant techniques to convert a string to a Boolean value in JavaScript with precise code explanations.

Converting a String to Boolean in JavaScript

JavaScript has several built-in methods and functions that convert strings into Boolean values. Here are some methods for the conversion:

  1. JSON.parse()
  2. Identity Operator
  3. Equality Operator
  4. test() method with Regex
  5. Boolean Wrapper Class
  6. tolowercase() method
  7. Ternary Operator
  8. Double Not Operator !! (not not)
  9. Switch-use

Method 1: Using JSON.parse() method

JSON parsing helps to convert a JSON object in text format to a JavaScript object, which users can use within the program. Users must write the string in JSON format. The method uses a function to convert the string object into the given JavaScript object. Thus, users can use it for the required conversion.

Syntax:

JSON.parse(string, function)

Parameters used:

  • string: This parameter is mandatory. It accepts the string written in JSON format.
  • function: This parameter is optional. This parameter converts the string object into a JavaScript object. The method will call this function for each element and converts all the nested elements before the parent.

If this parameter returns a valid value, the method will replace the element value with the transformed value. Else, on returning undefined, the method deletes the element.

Code Snippet:

let a = "true";
// Here, we declare a variable for storing Boolean values
let Boolean_value;
Boolean_value = JSON.parse(a);
console.log("Thus, we convert the string 'a' to Boolean using parse() method:", Boolean_value);

Output:

Run Code

Explanation:

The above example shows that using JSON.parse() method, users can easily convert strings to Boolean values. We passed a string value in the variable "a," which gets converted into the given JavaScript object, i.e., a Boolean value.

But remember, if we pass a number as input, the result of JSON.parse(a) will be of return type "number." And if we pass undefined, it will return a JSON.parse error.

Method 2: Using Identity Operator

The triple equals to, also known as the identity operator or strict equality operator, checks if the two operands that users pass into the operator are "identical." It uses a strict definition of sameness. Users must provide elements with the same values and data type to get true. Else, it will return false.

Thus, in the case of conversion, users can use it to convert a string to a Boolean. It will return true if the left-hand and the right-hand side are equal. Else, it will return false.

Syntax:

a===b

Code Snippet:

var a = "false";
// Here, we insert the string for the conversion
var b = "false";
// Here, we insert the Boolean value
var Boolean_value ;  
Boolean_value  = (a === b);
console.log("Converting the string values into Boolean value:", Boolean_value );

Output:

Run Code

Explanation:

We initialized two variables, "a" and "b." Both the variables have equal values, and the Boolean_value will compare the values of the variables using the strict equality operator. Since the values match, it will return true.

Method 3: Using Equality Operator

Users can use the comparison operator or double equals to the operator to perform logical operations similar to the strict equality operator. It compares the operands of the left-hand side with the right-hand side. It will return true if the left-hand and the right-hand side are equal. Else, it will return false.

Syntax:

a==b

Code Snippet:

// Here, we insert the string for the conversion
var a = "1";
// Here, we insert the Boolean value
var b = new Boolean(true);
var Boolean_value ;  
Boolean_value  = (a == b);
console.log("Converting the string value into Boolean value:", Boolean_value );

Output:

Run Code

Explanation:

As you can see, in the above example, we used two variables where the first variable, "a," has a string value with an integer.

The second variable has a Boolean value "true." In programming, we represent Yes or No, on or off and True or False in 1's and 0's. Thus, since we passed 1 and True, the comparison operator will return true.

Method 4: Using test() method with Regex

Regex, as we all know, is short for Regular expression and has patterns of characters. It allows users to match and check the string character combination. It uses the test() method for matching the given string. The method returns true if it finds a match, else false.

Syntax:

RegExpObject.test(a)

Code Snippet:

let a = "hello";
let Boolean_Value = (/hello/).test(a);
console.log(Boolean_Value);

Output:

Run Code

Code Snippet:

let a = "hello";
let Boolean_Value = (/Hello/).test(a);
console.log(Boolean_Value);

Output:

Run Code

Code Snippet:

let a = "hello";
let Boolean_Value = (/Hello/i).test(a);
console.log(Boolean_Value);

Output:

Run Code

Explanations:

In the above examples, we used three scenarios where the first code example returns true since we passed equal values in the variable "a" and the Regex. The second example returned false since the values have a case sensitivity.

Lastly, we passed the i flag at the end of the regular expression in the third example to avoid case sensitivity.

Code Snippet:

var a = "true";
var b = "false";
// Here, we create a regular expression object having "false"
var regex = new RegExp("false");
var res1 = regex.test(a);
var res2 = regex.test(b);
console.log("The variable 'a' converted to Boolean is:", res1);
console.log("The variable 'b' converted to Boolean is:", res2);

Output:

Run Code

Explanation:

Alternatively, we used two separate variables and passed a Regex pattern to match the strings in the initialized variables. We used the RegExp() constructor, which accepts the Regex pattern. Lastly, the test() method returns true and false after matching the values with the given Regex pattern.

Method 5: Using Boolean Wrapper Class

Users can use the object wrapper class, called JavaScript Boolean Wrapper. Though it helps to convert strings into Boolean values, experts do not prefer users to use it.

Because when users initialize a variable that contains "false," the Boolean wrapper returns true since the variable is not empty. Thus, in such cases, these confuse and generate errors.

The wrapper wraps around objects to transform them into Boolean objects. It accepts one element as its parameter. If users pass an empty element, the wrapper returns false. Else, it will return true, no matter what is inside the parameter.

Code Snippet:

var a = Boolean('JavaScript')
var b = Boolean('')
var c = Boolean(true)
console.log("It will convert the string 'JavaScript' into:", a);
console.log("The empty string returns:", b);
console.log("It will convert the string 'True' into:", c);

Output:

Run Code

Explanation:

Here, we initialized three variables with different values. The first variable contains string value which gets converted into Boolean true.

The second contains an empty string and returns false, and the third contains a Boolean true value which also returns true.

Method 6: Using the tolowercase() method

It is not a supreme idea to convert a string to a Boolean value using the tolowercase() method, but you can try this one too. This method takes string values and converts them into lowercase.

Syntax:

str.toLowerCase()

Code Snippet:

var a = 'TRUE'
var res = (String(a).tolowercase() === 'true');
console.log(res);

Output:

Run Code

Explanation:

Though this method is not the cleanest method, we used it to convert the given string to a Boolean value. First, we initialized a variable with a "true" value. The method checks the case-sensitivity of the string and converts it to lowercase.

Thus, it returns true. If users insert any other string value, the method will return false since it will only accept that value, which we provided with the strict equality operator.

Method 7: Using Ternary Operator

Using the ternary operator, users can input three operands, a conditional statement, an expression to run when the conditional statement returns correct, and the third to execute if the conditional statement is incorrect. Thus, users can use it to convert a string to a Boolean.

By passing the given string, the conditional statement will match it with "true." If the conditional is correct, the ternary operator will return true. Else, it will return false.

Syntax:

condition ? value if true : value if false
  • condition: It is the expression the operator will evaluate. It returns a Boolean value.
  • value if true: If the conditional result is true, the operator will execute this value.
  • value if false: If the conditional result is false, the operator will execute this value.

Code Snippet:

const a = "true";
var Boolean_value;
Boolean_value = (a == "true" ? true : false);
console.log("The Boolean value is:", Boolean_value);

Output:

Run Code

Explanation:

In this example, we used the ternary operator to convert the given string into a Boolean object. We initialized two variables, the first variable, "a," has "true." The second value uses the ternary operator. The conditional statement of the operator, i.e., the first parameter compares this string value with another string "true" using the equality operator (==).

The second parameter takes a Boolean value of true and the third parameter takes a Boolean value false. Since the first variable contains "true," the ternary operator's conditional became correct in this example. Thus, the operator returns true.

Method 8: Using Double Not Operator !! (not not)

It is similar to the Boolean Wrapper Class in JavaScript. The Double Not Operator (not not) is the logical repetition of the unary logical operator not (!) two times. The double negation (!!) operator evaluates the true value of a string. The operator returns a Boolean value, which relies on the truthiness of the provided expression.

In general, the double not operator specifies the "truth" of what a value is not not, i.e.:

  • It returns the truth value when the true is not not true (that is why !! true results in true)
  • It returns a false value when the false not not false (that is why !! false results in false)

Code Snippet:

var a = !!('Hello')
var b = !!('')
var c = !!('true')
console.log("The double not of ('Hello') returns -", a);
console.log("The double not of ('') returns -", b);
console.log("The double not of ('true') returns -", c);

Output:

Run Code

Explanation:

We initialized three variables, a, b, and c, in the above code snippet. Then we used the Double Not Operator (!!). The first variable contains string value which gets converted into Boolean true.

The second contains an empty string and returns false, and the third contains a "true" value which also returns true. When we converted the empty string to a Boolean object, the double not operator converts the string to false. It is why experts do not prefer users to use this operator.

Method 9: Using Switch-use

It is one of the best practices to use the switch-case to convert the string object to a Boolean value. It helps to work with decision-making purposes. Using this, users can also convert strings that contain "True," "1," and other values to Boolean true. On the other hand, users can use the opposite, i.e., false to Boolean false.

Syntax:

case value_1:
        statement_1;
        break;
    case value_2:
        statement_2;
        break;
    .
    .
    case value_n:
        statement_n;
        break;
    default:
        statementDefault;
}

Code Snippet:

	var a = "1";
	var b = "false";
	function demo(str){
		switch(str){
			case "TRUE":
				return true;
			case "1":
				return true;
			case "yes":
				return true;
			case "FALSE":
				return true;
			default:
				return false;
		} 
	}
	console.log('The string "1" gets converted to Boolean value as:', demo(a));
	console.log('The string "false" converted to Boolean value as:', demo(b));

Output:

Run Code

Explanation:

We have converted the two string values into Boolean values using this technique. We defined the demo function that contains the switch-case statement. We specified true with three values, i.e., “true," "1," and "yes." The other is false with value "0."

The switch-case evaluates the expression, matches the result with the five different case values, and returns the value of the statement that matches the correct case value.

Conclusion

When users want to perform Boolean operations on values stored in a string object, they first convert the string into Boolean value, i.e., true or false. This article has highlighted nine conversion techniques that can reach the correct conversion point of string to Boolean in JavaScript.

So, programmers can use the suitable method and convert the string to an array in the format they want according to their requirements.


×