How to convert string to boolean JavaScript

How to convert string to boolean JavaScript

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

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

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