Explain Codes LogoExplain Codes Logo

How can I convert a string to boolean in JavaScript?

javascript
boolean-conversion
javascript-operators
truthy-falsy-values
Anton ShumikhinbyAnton Shumikhin·Aug 28, 2024
TLDR

Free your memory of complex conversions and let the brevity of !! do the job. This double negation turns non-empty strings into true, and empty strings into false:

var boolValue = !!'Hello'; // true, friendly greeting granted var falseValue = !!''; // false, loneliness intensifies

But wait, you have explicit boolean strings "true" and "false"? Compare them directly:

var isTrueSet = (myValue === 'true'); // true if myValue is totally "true" var isFalseSet = (myValue === 'false'); // true if myValue is "false" (what a plot twist!)

Always remember, with great power (JavaScript) comes great responsibility (to avoid implicit conversions).

Detailed explanation

Literal comparison: Straight forward is the best forward

var isTrueSet = (myValue === 'true'); // true only if myValue is outright "true"

For case-insensitive users, the toLowerCase() function is your best friend:

var isTrueSet = (myValue.toLowerCase() === 'true'); // Unbiased case handling

Regular expressions: Making sure no strings are attached

Regex is your robust warrior, standing tall in scenarios asking for whitespace tolerance and different casing:

// Regex is like your overprotective friend, ignoring whitespace var isTrueSet = /^true$/i.test(myValue.trim());

Boolean constructors: Traps in the disguise of ease

Using Boolean(myValue) or !!myValue can act like a wolf in a sheep’s clothing for non-empty strings like "false", as they return true:

var falseStringToBoolean = Boolean("false"); // true, It's an 'Impasta'!

JSON parsing: When precision is the key

Remember, fine edges need careful handling. Use JSON.parse method only when you are dealing with boolean values in valid JSON format.

try { var parsedBool = JSON.parse(myValue); // Hoping for a "true" or "false" } catch (e) { // An error, myValue was not true to you }

Say yes to more

Up your game by optimizing 'yes', '1' and 'true' to return true and turn 'no', '0', 'false', 'null', 'undefined' to return false:

var mappedBool = /^(yes|1|true)$/i.test(myValue.trim()); // "yes" means "true" here

Operators: Shield and sword of your code

The nullish coalescing operator (??) and optional chaining (?.) comprise the glittering armor shielding your code from null and undefined values:

var safeBool = (myValue?.toLowerCase()?.() === 'true') ?? false; // Just in case myValue ghosts you

DOM interactions: Get, set, go!

Obtaining booleans from HTML forms is as easy as grabbing cookies from a jar:

var isChecked = document.myForm.IS_TRUE.checked; // boolean straight from the horse's mouth

Clarity delivered via switch

In the marathon of programming, switch statements can act as signposts providing a clear mapping of string inputs to boolean outputs:

function stringToBoolean(str) { switch (str.toLowerCase().trim()) { case 'true': case 'yes': case '1': return true; // Straight road to truth case 'false': case 'no': case '0': case 'null': case 'undefined': return false; // A big nothing default: return null; // Landing into oblivion } }

Say yes to flexibility

The inherent truthy and falsy values of JavaScript have got your back in lenient conversions:

var truthyBool = !!myValue; // All non-empty strings are welcomed here

But beware, your digital hero can unveil subtle bugs if 'false' strings ought to be explicitly recognized as false.