How can I convert a string to Boolean in JavaScript?
Explanation
To convert a string to Boolean we will first learn what is a string and what is Boolean.
So the string is a collection of objects. And that objects can be of different types such as int, float. Boolean, long char, etc. And Boolean means we have a value in ‘ true’ or ‘ false’. When we have a value of anything in this two-term at that time that is called Boolean. So to convert string to Boolean we have to do the step that is shown below:
var isTrueSet = (myValue === 'true');
using the identity operator (===
), which doesn’t make any implicit type conversions when the compared variables have different types.
And you should not use the statements as :
var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
You should probably be cautious about using these two methods for your specific needs.
Also read, What is the difference between call and apply?