JavaScript code recipe: convert string to boolean

Posted on January 19, 2021


When you need to convert a string representing boolean values like "true" or "false" into real boolean types, you can’t use direct comparison to true and false because all non-empty string data actually converts to true in JavaScript.

The code below will log “Andy” instead of “Zack” to the console:

let myString = "false"; // returns boolean true

if (myString) {
  console.log("Andy");
} else {
  console.log("Zack");
}

When you need to convert strings into booleans, you need to create a robust method as follows

String comparison

You can compare the string values into another string to get the boolean value like this:

let myString = "false";

if(myString === "true"){
  console.log("Andy");
} else {
  console.log("Zack");
}

Sometimes you may have a string value in uppercase. You need to convert the string into lower case during comparison:

let myString = "FALSE";

if(myString.toLowerCase() === "true"){
  console.log("Andy");
} else {
  console.log("Zack");
}

Finally, you may have several string values that you want to convert true, such as “yes”, “on”, or “1”. You can create a more robust solution by using the switch statement as follows:

let myString = "ON";

switch(myString.toLowerCase()){
  case "true":
  case "yes":
  case "on":
  case "1":
    console.log("Value is true");
    break;
  default:
    console.log("Value is false");
}

More on JavaScript:

Grab the free JavaScript book today 👍

Learn the building blocks of JavaScript programming language like data types, functions, objects, arrays and classes.

Use the knowledge from the book to build a small but solid program.

Learn more