How do you convert a string like "true" or "false" into a boolean in JavaScript?
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!)
You must log in or register to comment.
