How do you convert a string like "true" or "false" into a boolean in JavaScript? | A1Lab@FahadM to JavaScriptEnglish • 9 days ago

How do you convert a string like "true" or "false" into a boolean in JavaScript?

message-square
0

The safest way to convert “true” or “false” into a boolean in JavaScript is explicit string comparison: str.trim().toLowerCase() === “true”. Never use Boolean(“false”), because JavaScript treats every non-empty string as truthy and evaluates “false” to true.

Avoiding the Boolean(“false”) Truthy Trap Boolean() checks whether a string has characters rather than reading its text meaning. Normalizing whitespace and casing before checking === “true” ensures predictable results for form inputs, query params, and config flags.

JavaScript
function parseBoolean(value) {
  if (typeof value === "boolean") return value;
  if (typeof value !== "string") return false;
  return value.trim().toLowerCase() === "true";
}

console.log(parseBoolean("true"));      // true
console.log(parseBoolean(" TRUE "));    // true
console.log(parseBoolean("false"));     // false
console.log(Boolean("false"));          // true (common bug!)