Tuesday , January 23 2018
Home / JavaScript / Javascript convert string to boolean

Javascript convert string to boolean

So Many people have been asking me for various methods to convert string to Boolean in JS. Since there isn’t any built in library function thus we will explain you the trick to convert string variable to boolean type.

So wehave one function Boolean() that returns true for any non empty string. Below is the syntax with example:

var tempbool = Boolean(“true”); // “true” can also be ‘true’

All the following statements return true using Boolean() function in JavaScript.

var tempbool = Boolean('true');   // returns true
 var tempbool = Boolean('false');  //also returns true
 var tempbool = Boolean('anynonemptystring');  // returns true

Thus due to this limitation we have to play it tricky and trust me its damn simple. You first need to check the string with true or false value using a conditional operator! Confused how? Check below-

Also See:   Loan EMI Calculator Script and Widget


var temp = 'true';
var tempbool = (temp == 'true'); // read the below explanation before use


Above code returns true to the variable tempbool if temp value is equal to ‘true’, other wise it returns false.   

Do check the live code for better understanding

This is the best way of converting string to boolean.

Thanks and do comment your views on this.

Leave a Reply

Your email address will not be published. Required fields are marked *