Home

Parse String to Boolean using JSON.parse()

JSON.parse() is able to convert a string to boolean easily while retaining its value.

let strTrue = "true";
let strFalse = "false";
 
console.log(JSON.parse(strTrue)); // true
console.log(JSON.parse(strFalse)); // false

While working on environment variables using process.env from a .env file, I realised that I had to use strict equal process.env.SOME_VARIABLE === "true" in order to make the condition as a valid boolean since environment variables are typeof String. While finding a better way around this, I came across using the JSON.parse() way that seems to make it easier. I was able to write a reusable function to make things easier for me too.

SOME_VARIABLE=true
const isFeatureEnabled = (feature: string): boolean => {
  return JSON.parse(feature);
};
 
isFeatureEnabled(process.env.SOME_VARIABLE); // true

Let me know how other ways do you handle converting a string of values "true" or "false" to their boolean values.