JavaScript code recipe: convert string to boolean

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");
}

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

No spam. Unsubscribe anytime.