Question

How to Convert a String to Boolean in JavaScript

javascriptboolean-expressionboolean-operationsstring-conversion

Question

In JavaScript, how can I convert a string that represents a boolean value, such as 'true' or 'false', into an actual boolean?

For example, I have an HTML form with hidden inputs that are updated based on a user's selection. Some of these fields represent boolean values. Even if I assign a real boolean to the input, once it is stored in the form field, it becomes a string.

Right now, I am checking the value like this:

var myValue = document.myForm.IS_TRUE.value;
var isTrueSet = myValue == 'true';

Is there a better or more reliable way to handle this conversion in JavaScript?

Short Answer

By the end of this page, you will understand how boolean-like strings work in JavaScript, why form inputs always return strings, and how to safely convert values like 'true' and 'false' into real booleans. You will also learn common mistakes, practical patterns, and when a direct string comparison is actually the correct solution.

Concept

In JavaScript, a boolean is a real primitive value: true or false.

A string is text, even if that text looks like a boolean:

true      // boolean
' true '  // string
'false'   // string

This matters because HTML form fields return their values as strings. So if an input contains true, JavaScript usually reads it as 'true', not the boolean true.

A very important detail is that JavaScript's built-in truthiness rules are not the same as converting 'true' / 'false' text into booleans.

For example:

Boolean('true');  // true
Boolean('false'); // also true

Why? Because any non-empty string is truthy in JavaScript.

So if your goal is:

  • 'true' -> true
  • 'false' -> false

then you should usually compare the string explicitly:

const result = value === 'true';

That works because only the exact string 'true' becomes true. Everything else becomes false.

This concept matters in real programming because values often cross boundaries:

  • HTML forms
  • URL query parameters
  • localStorage
  • JSON APIs
  • dataset attributes
  • environment variables

Many of these sources give you strings, even when the original meaning was boolean. Knowing how to convert them correctly prevents subtle bugs.

Mental Model

Think of a form input like a label printer that turns everything into text.

Even if you put a real boolean into it, when you read it back, you get a text label:

  • true becomes 'true'
  • false becomes 'false'

Your job is to read the label and decide what it means.

A good mental model is:

  • Boolean value = the actual on/off switch
  • Boolean string = a note stuck onto the switch saying 'true' or 'false'

You should not ask, "Is this note non-empty?" because both 'true' and 'false' are non-empty strings.

Instead, ask, "Does the note exactly say 'true'?"

Take Quiz

Syntax and Examples

The safest beginner-friendly approach is explicit comparison.

Basic conversion

const value = 'true';
const boolValue = value === 'true';

console.log(boolValue); // true
const value = 'false';
const boolValue = value === 'true';

console.log(boolValue); // false

Reading from a form field

const myValue = document.myForm.IS_TRUE.value;
const isTrueSet = myValue === 'true';

This is better than using == because === checks both value and type without coercion.

Handling different capitalizations

If your input might contain values like 'True' or 'TRUE', normalize it first:

const value = 'TRUE';
const boolValue = value.toLowerCase() === 'true';

console.log(boolValue); // true

Safer helper function

function parseBoolean(value) {
  return String(value).toLowerCase() === 'true';
}

console.log(parseBoolean('true'));  // true
console.log(parseBoolean('false')); // false
console.log(parseBoolean(true));    // true
console.log(parseBoolean(false));   // false

What not to do

Boolean('false'); // true

This is a common mistake. Boolean() checks truthiness, not the text meaning of the string.

Step by Step Execution

Consider this example:

const inputValue = 'false';
const result = inputValue === 'true';
console.log(result);

Step by step:

  1. inputValue is assigned the string 'false'.
  2. JavaScript evaluates inputValue === 'true'.
  3. It compares:
    • left side: 'false'
    • right side: 'true'
  4. The two strings are not equal.
  5. The expression returns the boolean false.
  6. result now stores the real boolean false.
  7. console.log(result) prints false.

Now compare with this broken approach:

const inputValue = 'false';
const result = Boolean(inputValue);
console.log(result);

What happens here:

  1. inputValue is 'false'.
  2. Boolean(inputValue) checks whether the string is truthy.
  3. 'false' is a non-empty string.
  4. All non-empty strings are truthy.
  5. So the result is true.

That is why Boolean(value) is not the right tool for parsing boolean-like strings.

Real World Use Cases

Boolean string conversion appears often in everyday JavaScript work.

Form handling

Hidden inputs, text inputs, and select values are returned as strings:

const isAdmin = document.querySelector('#isAdmin').value === 'true';

Query parameters

A URL may contain values like ?debug=true:

const params = new URLSearchParams(window.location.search);
const debug = params.get('debug') === 'true';

localStorage

Values in localStorage are always stored as strings:

localStorage.setItem('darkMode', 'false');
const darkMode = localStorage.getItem('darkMode') === 'true';

API responses

Sometimes older APIs return booleans as strings instead of real booleans:

const isEnabled = apiResponse.enabled === 'true';

Data attributes

HTML data-* attributes are also strings:

const isVisible = element.dataset.visible === 'true';
Take Quiz

Real Codebase Usage

In real projects, developers usually avoid "magic conversion" and use explicit parsing.

Common pattern: strict comparison

const isPublished = formData.status === 'true';

This is readable and predictable.

Common pattern: helper function

If parsing happens in many places, teams often create a utility:

function parseBoolean(value) {
  return String(value).trim().toLowerCase() === 'true';
}

This centralizes the rule and makes behavior consistent.

Validation before conversion

In larger codebases, values may be validated first:

function parseBoolean(value) {
  const normalized = String(value).trim().toLowerCase();

  if (normalized !== 'true' && normalized !== 'false') {
    throw new Error('Invalid boolean string');
  }

  return normalized === 'true';
}

This is useful when bad input should be rejected instead of silently treated as false.

Guard clauses

function handleSetting(value) {
  if (value == null) {
    return false;
  }

  return String(value).toLowerCase() === 'true';
}

Guard clauses make edge cases easier to read.

JSON as a better format

If you control both sides of the data, sending real booleans in JSON is often better than sending 'true' and 'false' strings:

const settings = { darkMode: true };
const json = JSON.stringify(settings);
const parsed = JSON.parse(json);

console.log(parsed.darkMode); // true

In real codebases, the best solution is often to avoid boolean strings entirely when possible.

Common Mistakes

1. Using Boolean() to parse 'false'

Broken code:

const value = 'false';
const result = Boolean(value);
console.log(result); // true

Why it fails:

  • Boolean() checks truthiness
  • any non-empty string is truthy

Use this instead:

const result = value === 'true';

2. Using loose equality ==

const isTrueSet = myValue == 'true';

This may work here, but strict equality is better practice:

const isTrueSet = myValue === 'true';

3. Forgetting about capitalization

Broken code:

const value = 'TRUE';
const result = value === 'true'; // false

Fix:

const result = value.toLowerCase() === 'true';

4. Ignoring whitespace

Broken code:

const value = ' true ';
const result = value === 'true'; // false

Fix:

const result = value.trim().toLowerCase() === 'true';

5. Assuming form values keep their original type

Form fields always give you strings:

const value = document.querySelector('input').value;
console.log(typeof value); // string

Always parse the value if you need another type.

6. Silently treating invalid values as false

function parseBoolean(value) {
  return String(value).toLowerCase() === 'true';
}

This makes 'yes', '1', and 'abc' all become false.

That may be okay, but in some cases you should validate instead:

function parseBoolean(value) {
  const normalized = String(value).trim().toLowerCase();

  if (normalized !== 'true' && normalized !== 'false') {
    throw new Error('Expected true or false');
  }

  return normalized === 'true';
}

Comparisons

ApproachExampleResult for 'true'Result for 'false'Good for parsing boolean strings?
Strict comparisonvalue === 'true'truefalseYes
Loose comparisonvalue == 'true'truefalseWorks, but not preferred
Boolean(value)Boolean('false')truetrueNo
Double negation!!valuetruetrueNo
JSON parsingJSON.parse('true')truefalseSometimes

value === 'true' vs JSON.parse(value)

const a = 'true';
console.log(a === 'true');     // true
console.log(JSON.parse(a));    // true

But JSON.parse() is only safe if the string is valid JSON:

JSON.parse('false'); // false
JSON.parse('true');  // true
JSON.parse('hello'); // error

So for simple form handling, direct comparison is usually clearer.

=== vs ==

OperatorMeaningRecommendation
===strict equality, no type coercionPreferred
==loose equality, allows type coercionAvoid when possible

In this case, === is the better habit.

Take Quiz

Cheat Sheet

// Best simple conversion
const boolValue = value === 'true';

// Safer when case/spacing may vary
const boolValue = String(value).trim().toLowerCase() === 'true';

Key rules

  • Form input values are strings.
  • 'true' and 'false' are not booleans.
  • Boolean('false') is true because it is a non-empty string.
  • Use === 'true' for explicit conversion.
  • Use trim() and toLowerCase() if input format may vary.

Useful helper

function parseBoolean(value) {
  return String(value).trim().toLowerCase() === 'true';
}

Strict validating helper

function parseBooleanStrict(value) {
  const normalized = String(value).trim().toLowerCase();

  if (normalized !== 'true' && normalized !== 'false') {
    throw new Error('Invalid boolean string');
  }

  return normalized === 'true';
}

Avoid

Boolean(value);
!!value;

These check truthiness, not string meaning.

FAQ

Why does 'false' become true with Boolean()?

Because 'false' is a non-empty string, and all non-empty strings are truthy in JavaScript.

Is value === 'true' a valid way to convert a string to boolean?

Yes. If your input is expected to be 'true' or 'false', this is often the clearest solution.

Should I use == or === for boolean string comparison?

Use ===. It avoids type coercion and is more predictable.

Can I use JSON.parse() to convert 'true' and 'false'?

Yes, but only if the string is guaranteed to be valid JSON like 'true' or 'false'. It is less forgiving and may throw errors for invalid input.

Why do HTML input values always come back as strings?

Form fields represent text values in the DOM API, so .value returns a string.

How do I handle 'TRUE' or ' True '?

Normalize the string first:

const result = String(value).trim().toLowerCase() === 'true';

What if I want invalid values to cause an error?

Use a strict parser that only accepts 'true' and 'false', and throws an error for anything else.

Take Quiz

Mini Project

Description

Build a small settings parser for a web page. The page receives values such as darkMode, emailAlerts, and debug from hidden inputs or another string-based source. Your task is to convert those string values into real booleans safely and display the parsed result. This project demonstrates a practical use of boolean string parsing in frontend JavaScript.

Goal

Create a JavaScript utility that converts boolean-like strings into real booleans and uses it to read multiple settings values.

Requirements

  • Create a parseBoolean function that converts 'true' and 'false' strings to booleans.
  • Normalize input so values like 'TRUE' and ' false ' are handled correctly.
  • Read at least three string values from an object that simulates form input.
  • Store the parsed results in a new object.
  • Print the final parsed settings to the console.
Take Quiz

Keep learning

Related questions

View more