JavaScript - How to Convert the String to a Boolean
Learn, how to convert a string to boolean value in JavaScript with the help of examples.
To convert a string to a boolean, we can use the triple equals operator ===
in JavaScript.
The triple equals (===) operator in JavaScript helps us to check both type and value, so it returns “true” when both side values have same type and value otherwise it returns “false”.
Here an example:
let a = 'true';
let result = a === 'true';
console.log(result);
Output:
true
In above code, we are comparing the string to the string value'true'
. If the both values are same the condition will return boolean value true otherwise false.
The triple equals operator checks both left hand side operator and right hand side operator should be same. If both are same it returns true otherwise it returns false.
Similarly, we have also other way to convert the string to boolean using the JavaScript Boolean() constructor.
The JavaScript Boolean() constructor takes the string as an argument and returns the boolean representation of it.
Here is an example:
let user = "Gowtham";
let result = Boolean(user);
console.log(result);
Output:
true