Convert string to boolean in javascript

In this article i am going to explain how to Convert string to Boolean in JavaScript.

There is no built-in function in JavaScript to Convert a string to Boolean.

Be careful when using following method in JavaScript.

var boolValue = Boolean("true");

The above Boolean() method, any string which is not empty will be evaluated to true.

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

var boolValue = Boolean('true');   // true
var boolValue = Boolean('false');  //true
var boolValue = Boolean('someOtherString');  //true

So, only easy and trusted way to Convert a string to Boolean in JavaScript is by checking string value manually.

var myString = 'true';

var boolValue = (myString == 'true');

Above statement returns true if myString value is equal to 'true', other wise it returns false.   

For live example visit the following JSFiddle : Convert string to boolean in javascript

In this way we can Convert a string to Boolean in JavaScript.

please leave comment for any queries or suggestions.

For more posts on JavaScript visit: JavaScript

1 comment:

  1. var myB01 = Boolean(""); // Returns false. Because empty string
    var myB02 = Boolean(null); // Returns false. Because null
    var myB03 = Boolean(undefined); // Returns false. Because undefined

    JavaScript Training