In this tutorial let’s learn about How to Convert a String to Boolean in JavaScript. JavaScript has several methods for converting a string to a boolean, but it depends on the situation or, in other words, on your goal for converting a string to a boolean, as we will see below.
Contents
Convert a String to a Boolean Value ( True or False ) in JavaScript
The simplest approach to convert a string to a boolean is to compare it to ‘true
‘:
let myBool = (str=== 'true');
For a more case insensitive approach use .toLowerCase()
function:
let myBool = (str.toLowerCase() === 'true');
If str
is null or undefined, toLowerCase() will return an error.
Code example:
let str = 'true';
let value = (str.toLowerCase() === 'true'); // true
console.log(value);
str = 'None';
value = (str.toLowerCase() === 'true'); // false
console.log(value);
str = 'Value';
value = (str.toLowerCase() === 'value'); // true
console.log(value);
Output:
true
false
true
Convert the String to Boolean using !! in JavaScript
There are two methods for converting variables to Boolean values. First, by using dual NOT operators (!! ), and then by using typecasting (Boolean(value)).
Code Example :
let value = Boolean("false");
let myBool = !!"false";
console.log({value, myBool});
Output :
{ value: true, myBool: true }
Because “false” is a string in the preceding example, Boolean(“false”) returns true.
You should probably avoid using these two techniques for the first scenario because they will evaluate to true any string that isn’t the empty string.
How the !!
works
The first! converts the value to a boolean and then inverses it. !value will return false in this scenario. So to reverse it back to true, we placed another ! on it. As a result, the double usage!!
const value = 'javascript';
!value; // false
!!value; // true
Another example:
const mybool= 'false';
!!mybool; // true
Boolean(mybool); // true
Conclusion
Looks like the !!
is a faster than Boolean
method. In this tutorial we have gone through different ways of Converting a String to Boolean in JavaScript.
Similar Posts:
Capitalize the First Letter of a String in JavaScript
How to Convert a String Into Date in JavaScript