• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Basics / How To Convert a String to Boolean in JavaScript

How To Convert a String to Boolean in JavaScript

How To Convert a String to Boolean in JavaScript

JavaScript has several ways to convert a string to a boolean. One way is to use the Boolean() function, which returns the boolean value of a given variable. For example:

let str = "true";
let bool = Boolean(str);
console.log(bool); // outputs: true

Another way is to use the == or === operator to compare the string to the boolean values true or false. The == operator performs type coercion, meaning it will try to convert the string to a boolean before comparing it. The === operator, on the other hand, does not perform type coercion and compares the string and boolean values directly.

let str = "true";
let bool = (str == true);
console.log(bool); // outputs: true
let str = "true";
let bool = (str === true);
console.log(bool); // outputs: false

Another way to convert string to boolean is using JSON.parse() method which parses a string as JSON and returns JavaScript objects.

let str = "true";
let bool = JSON.parse(str);
console.log(bool); // outputs: true

You can also use if(str) statement. In this case if the string is “truthy” it will return true, otherwise false.

let str = "true";
if(str) {
    console.log(true);
}
else {
    console.log(false);
} // outputs: true

In JavaScript, the following values are considered “falsy”:

  • false
  • 0 (zero)
  • "" (empty string)
  • null
  • undefined
  • NaN

So, if you use if(str) statement, it will return true for any string which is not “falsy”.

It is important to note that when using the == operator, the string “false” will be considered true because it is not one of the falsy values listed above. To avoid this, it is best to use the === operator or the Boolean() function when converting strings to booleans in JavaScript.

Basics, Miscellaneous

Related Snippets:

  • Replace a portion of a string with something else
  • The onabort Event in JavaScript
  • Comparison and Logic Operators in JavaScript
  • Convert a string to a number

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers