convert string to boolean in javascript

How to Convert String to Boolean in JavaScript

Sometimes you may end up with a string representation of Boolean values such as ‘true’ or ‘false’. If you directly use them in your JS code for Boolean values, you may get an error. In such cases, you need to convert string to Boolean in JavaScript. In this article, we will learn how to convert string to Boolean in JavaScript.


How to Convert String to Boolean in JavaScript

Let us say you have the following string that contains Boolean value.

var test = 'true';

Here is a command to convert it into Boolean values.

var test_boolean = (test === 'true'); // returns true

In the above command, we basically check the value of test variable against string using === operator, which returns Boolean true in case of equality, else it returns Boolean false. Since we use identity operator (===) it does not do type conversion in case the variable is not a string.

Alternatively, you can also use equality operator to do the comparision.

var test_boolean = (test == 'true');

Similarly, if your string has a different case of string, you need to modify your expression accordingly. Here is an example if your variable is ‘TRUE’.

var test_boolean = (test === 'TRUE');

In this article, we have learnt how to convert string to Boolean in JavaScript. The key is to explicitly compare a string variable with a literal string or variable so that the result is a Boolean value.

Also read:

How to Convert Decimal to Hexadecimal in JS
How to Add 30 Minutes to JS Date Object
How to Measure Time Taken in JS Function
How to Replace Part of String in Update Query
How to View Live MySQL Queries

Leave a Reply

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