Converting from string to boolean in javascript is not a huge task. There are many methods in JavaScript to do this. In this tutorial, you will learn how to convert string to boolean using built in methods of JavaScript.
How to convert string to boolean JavaScript
By using the following methods, you can quickly convert string to boolean in javascript:
- Method 1: Using the Boolean() function
- Method 2: Using the !! operator
- Method 3: Using a ternary operator
Method 1: Using the Boolean() function
You can easily convert a string to a boolean value in JavaScript using the built in boolean() method.
Here’s an example to convert a string to a boolean value in JavaScript using the built in boolean() method:
let str = "false"; let bool = Boolean(str); console.log(bool); // logs false str = "true"; bool = Boolean(str); console.log(bool); // logs true
Method 2: Using the !! operator
Second method to convert a string to a boolean value in JavaScript is by using the !! operator.
Here’s an example to convert a string to a boolean value in JavaScript using the !! operator:
let str = "false"; let bool = !!str; console.log(bool); // logs false str = "true"; bool = !!str; console.log(bool); // logs true
Method 3: Using a ternary operator
A third method to convert a string to a boolean value in JavaScript is by using a ternary operator.
Here’s an example to convert a string to a boolean value in JavaScript using a ternary operator:
let str = "false"; let bool = str === "true" ? true : false; console.log(bool); // logs false str = "true"; bool = str === "true" ? true : false; console.log(bool); // logs true
Conclusion
In this tutorial, you have learned several different methods for converting a string to a boolean value in JavaScript. Whether you prefer to use the built-in Boolean() function, the !! operator, or a ternary operator, there’s no shortage of options available.