How to convert string to boolean JavaScript

You can use the Boolean() function to convert a string to a boolean in JavaScript.

Example:

let str = “true”;
let booleanValue = Boolean(str);

console.log(booleanValue); // Output: true

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.

Recommended Tutorials

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?