Open In App

JavaScript Convert a string to boolean

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To Convert a string to Boolean, we have multiple approaches. We are going to learn how to Convert a string to Boolean.

Below are the approaches used to Convert a string to Boolean:

Approach 1: Using JavaScript == Operator

This operator compares the equality of two operands. If equal then the condition is true otherwise false. 

Example: This example uses the == operator to convert a string to its boolean value. 

Javascript




let str1 = "true";
console.log(str1 == 'true');
 
let str2 = "True";
console.log(str2.toLowerCase() == 'true');


Output

true
true

Approach 2: Using JavaScript === Operator

This operator compares the equality of two operands with type. If equal(type and value both) then the condition is true otherwise false. 

Example: This example uses the === operator to convert the string to its boolean value. 

Javascript




let str = "true";
console.log(str === 'true');
 
str = "True";
console.log(str.toLowerCase() === 'true');


Output

true
true

Approach 3: Using the Boolean() function

The boolean function returns the boolean value of the variable. It can also be used to find the boolean result of a condition, expression, etc. The Boolean() function evaluates the input and returns a boolean value. In this case, since the input string “true” is non-empty, the Boolean() function returns true.

Example: In this example, we are using the above-explained approach.

Javascript




let str = "true";
let result = Boolean(str);
console.log(result);


Output

true

Approach 4: Using a regular expression

In this approach regular expression to convert a string to a boolean value in JavaScript.

Example: In this example, the regular expression /^true$/i is used with the test() method to check if the string matches the pattern “true” (case-insensitive). The ^ symbol denotes the start of the string, $ denotes the end of the string, and the i flag makes the pattern case-insensitive.

Javascript




let str = "true";
let boolValue = /^true$/i.test(str);
console.log(boolValue);


Output

true

Approach 5: Using the !! (double negation) operator

The !! (double negation) operator is a commonly used approach to convert a string to a boolean value in JavaScript

Example: In this example, The first negation (!) converts the string into its opposite boolean value, and the second negation (!) reverts it back to the original boolean value.

Javascript




let str = "true";
let boolValue = !!str;
console.log(boolValue);


Output

true

Approach 6: Using JSON.parse()

The JSON.parse() method can be used to convert a string to a boolean value in JavaScript. JSON.parse() method is used to parse the string “true” and convert it into its corresponding boolean value, which is true.

Example: In this example, we are using the above-explained approach.

Javascript




let str = "true";
let boolValue = JSON.parse(str);
console.log(boolValue);


Output

true

Approach 7: Using Ternary Operator

When using the ternary operator to convert a string to a boolean, the code employs a concise one-liner. The toLowerCase() method is applied to ensure case-insensitive comparison. The ternary operator checks if the lowercase string is equal to ‘true’. If the condition is met, it returns true; otherwise, it returns false.

Example: In this example, the toLowerCase() method is used to ensure case-insensitive comparison. The ternary operator checks if the lowercase string is equal to ‘true’ and returns true if it is, otherwise false.

Javascript




function stringToBooleanTernary(str) {
    // Ternary operator: condition ? true-value : false-value
    return str.toLowerCase() === 'true' ? true : false;
}
 
// Example usage:
const resultTernary = stringToBooleanTernary('True');
console.log(resultTernary); // Output: true


Output

true

Approach 8: Using Switch Case

The switch case approach involves using a switch statement to evaluate the lowercase string. Cases are defined for ‘true’ and ‘false’, each returning the corresponding boolean value. The default case is included to handle invalid input by throwing an error.

Example: In this example, the switch statement is used to evaluate the lowercase string. Cases for ‘true’ and ‘false’ return the corresponding boolean values, and the default case throws an error for an invalid string.

Javascript




function stringToBooleanSwitch(str) {
    switch (str.toLowerCase()) {
        case 'true':
            return true;
        case 'false':
            return false;
        default:
            throw new Error('Invalid boolean string');
    }
}
 
// Example usage:
try {
    const resultSwitch = stringToBooleanSwitch('False');
    console.log(resultSwitch); // Output: false
} catch (error) {
    console.error(error.message);
}


Output

false


Similar Reads

Explain non-boolean value coercion to a boolean one in JavaScript
As we all know javascript is a forgiving language. It does not mind silly mistakes which programmers do. So, sometimes it gives unexpected results. So it senses Javascript says "I can do every possibility". Coercion is one of those in which javascript gives weird results because javascript automatically performs type conversion in which first value
3 min read
Convert boolean result into number/integer in JavaScript
A JavaScript boolean represents one of two values: true or false. However, if one wants to convert a variable that stores boolean value, into integer "0" or "1", they can do so using multiple approaches. We will look into some of them in this article. The most popular methods are: Using ternary or conditional operator Using unary + operator. Using
3 min read
How to convert Number to Boolean in JavaScript ?
We convert a Number to Boolean by using the JavaScript Boolean() method and double NOT operator(!!). A JavaScript boolean results in one of two values i.e. true or false. However, if one wants to convert a variable that stores integer “0” or “1” into Boolean Value i.e. "false" or "true".  Below are the approaches: Table of Content Boolean() methodU
2 min read
How to convert string to boolean in PHP?
Given a string and the task is to convert given string to its boolean. Use filter_var() function to convert string to boolean value. Examples: Input : $boolStrVar1 = filter_var('true', FILTER_VALIDATE_BOOLEAN); Output : true Input : $boolStrVar5 = filter_var('false', FILTER_VALIDATE_BOOLEAN); Output : false Approach using PHP filter_var() Function:
2 min read
How to Convert String to Boolean in TypeScript ?
In Typescript, sometimes you receive the data as strings but need to work with boolean values or identify the boolean equivalent of it. There are several approaches to convert string to boolean in TypeScript which are as follows: Table of Content Using Conditional StatementUsing JSON.parse() MethodUsing Type AssertionUsing Regular ExpressionsUsing
3 min read
JavaScript Program for Boolean to String Conversion
This JavaScript program is designed to convert a boolean value to its corresponding string representation. In JavaScript, boolean values can either be true or false. The goal is to create a function that takes a boolean input and returns a string representation of that boolean value ("true" for true, and "false" for false). Below are the methods to
1 min read
JavaScript Boolean valueOf() Method
The boolean.valueOf() method is used to return a boolean value either "true" or "false" depending upon the value of the specified boolean object. Syntax: boolean.valueOf() Parameter: This method does not accept any parameter. Return value: It returns a boolean value either "true" or "false" depending upon the value of the specified boolean object.
4 min read
JavaScript Boolean toString() Method
The boolean.toString() method is used to return a string either "true" or "false" depending upon the value of the specified boolean object. Syntax: boolean.toString() Parameter: This method does not accept any parameter. Return Values: It returns a string either "true" or "false" depending upon the value of the specified boolean object. Below are e
3 min read
JavaScript Boolean() Constructor
The Boolean() constructor in JavaScript is a built-in function that can be used to create a new Boolean object. The Boolean() constructor takes a single argument and returns a Boolean object with a value of true or false depending on the type and value of the argument passed in. Syntax: Boolean(value) Parameter: This constructor accepts a single ar
1 min read
JavaScript Boolean Constructor Property
JavaScript boolean constructor property returns the constructor function for an object. The function which is returned by this property is just the reference to this function, not a Boolean containing the function’s name The JavaScript number constructor, string constructor, and boolean constructor return function Boolean() { [native code] }, funct
1 min read