Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to convert string to boolean JavaScript

Nouman Abbasi

In this shot, we will cover how to convert a string into its boolean representation.

The easiest way to convert string to boolean is to compare the string with 'true':

let myBool = (myString === 'true');

For a more case insensitive approach, try:

let myBool = (myString.toLowerCase() === 'true');

However, toLowerCase() will throw an error if myString is null or undefined.

Remember, all other strings that are not 'true' will be converted to false, e.g., ('Test'.toLowerCase() === 'true') evaluates to false.

we can also use !! for a string to boolean conversion.

Code

let myString = 'true';
let myBool = (myString.toLowerCase() === 'true'); // true
console.log(myBool);

myString = 'False';
myBool = (myString.toLowerCase() === 'true'); // false
console.log(myBool);

myString = 'Test';
myBool = (myString.toLowerCase() === 'true'); // false
console.log(myBool);

RELATED TAGS

javascript

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring