JavaScript Convert a string to boolean
Sometimes it is needed to convert a string representing a boolean value “true”, or “false” into the intrinsic type of JavaScript. In this article, we are given a string and the task is to convert the given string to its boolean value. There are two methods to do so:
- Using Javascript == operator
- Using Javascript === operator
Using Javascript == operator: This operator compares the equality of two operands. If equal then the condition is true otherwise false.
Example: This example uses the == operator to convert a string to its boolean value.
html
<body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>Convert string to boolean</h3> <input id="input" type="text" name="input" /> <button onclick="convertToBoolean()"> Click to convert </button> <h3 id="div" style="color: green"></h3> <!-- Script to convert string to its boolean value --> <script> function convertToBoolean() { var input = document.getElementById("input"); var x = document.getElementById("div"); var str = input.value; x.innerHTML = str == 'true'; } </script></body> |
Output:

Using Javascript === operator: This operator compares the equality of two operands with type. If equal(type and value both) then the condition is true otherwise false.
Example: This example uses the === operator to convert the string to its boolean value.
html
<body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <h3>Convert string to boolean</h3> <input id="input" type="text" name="input" /> <button onclick="convertToBoolean()"> Click to convert </button> <h3 id="div" style="color: green"></h3> <!-- Script to convert string to its boolean value --> <script> function convertToBoolean() { var input = document.getElementById("input"); var x = document.getElementById("div"); var str = input.value; x.innerHTML = str === 'true'; } </script></body> |
Output:







Please Login to comment...