How can I convert a string to boolean in JavaScript?

Can I convert a string representing a boolean value (e.g., 'true', 'false') into a intrinsic type in JavaScript?

I have a hidden form in HTML that is updated based upon a user's selection within a list. This form contains some fields which represent boolean values and are dynamically populated with an intrinsic boolean value. However, once this value is placed into the hidden input field it becomes a string.

The only way I could find to determine the field's boolean value, once it was converted into a string, was to depend upon the literal value of its string representation.

var myValue = document.myForm.IS_TRUE.value;
 var isTrueSet = myValue == 'true';
 

Is there a better way to accomplish this?

Text Copied From stackoverflow.com
on : Wed, Nov 05, 2008 Views : 1213075

Accepted Answer

Do:

var isTrueSet = (myValue == 'true');
 

Unnecessary:

You could make it stricter by using the identity operator (===), which doesn't make any implicit type conversions when the compared variables have different types, instead of the equality operator (==), which does:

var isTrueSet = (myValue === 'true');
 

Don't:

You should probably be cautious about using these two methods for your specific needs:

var myBool = Boolean(false);
  
// == true  var myBool = !!false;
  
// == true 

Any string which isn't the empty string will evaluate to true by using them. Although they're the cleanest methods I can think of concerning to boolean conversion, I think they're not what you're looking for.

Text Copied From stackoverflow.com
on : Wed, Nov 05, 2008

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links

E-Magazines

@

Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..

Ok

Login to Open ESchool OR Create your account    Login   SignUp