TypeScript & JavaScript · T11

Why is Boolean("false") true?

The string "false" is non-empty, so converting it with Boolean or !! returns true. Neither operation parses the meaning of the word.

The important bit
For a flag accepting only "true" or "false", validate the input before comparing it. Missing and invalid values need an explicit policy.

Understand it. Then fix it.

The useful part

The string "false" is non-empty, so converting it with Boolean or !! returns true. Neither operation parses the meaning of the word.

Make the rule explicit

For a flag accepting only "true" or "false", validate the input before comparing it. Missing and invalid values need an explicit policy.

function parseFlag(value) {
  if (value !== "true" && value !== "false") {
    throw new Error("Expected true or false");
  }
  return value === "true";
}

Code blocks are teaching excerpts. Keep the surrounding error handling and application requirements.

Save the code excerpts ↓
Read the full transcript

I set party to false. Why is my website still throwing confetti? Because the URL gives you a string. Boolean doesn't read English. Every non-empty string is truthy. Even false. So double exclamation marks won't fix it? Same conversion. Parse the value instead. Accept true. Accept false. Reject anything else. Here, a missing parameter defaults to false. Read party from the URL, then call the parser. Same URL, party equals false. Now the confetti stops. Uppercase and empty strings are rejected in this example. Great. My feature flag was a party invitation.

Go to the source