How to convert a string to a boolean in JavaScript

October 13, 2022 No comments javascript boolean-expression boolean-operations string-conversion

Introduction

In JavaScript, we may wish to convert a string to a boolean. In this post, we'll look at how to do it.

How to convert a string to a boolean in JavaScript

To convert a string to a boolean in JavaScript you need to:

  • check if your string is not null or undefined,
  • convert the string to lowercase,
  • compare converted string with true value.
const isTrue = (str) => str && str.toLowerCase() === 'true';

console.log(isTrue('test')); // false
console.log(isTrue('TRUE')); // true
console.log(isTrue('false')); // false
console.log(isTrue('0')); // false
console.log(isTrue('1')); // false
console.log(isTrue('True')); // true

Conclusion

In this article, we learned how to convert a string to a boolean in JavaScript.

{{ message }}

{{ 'Comments are closed.' | trans }}