πŸŽ„ Get 20% off from our JavaScript course for the holidays! πŸŽ„
How to Convert Anything to Boolean in JavaScript

How to Convert Anything to Boolean in JavaScript

Ferenc Almasi β€’ Last updated 2020 September 28 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

To convert anything to a boolean value in JavaScript, simply prepend it by two exclamation marks:

Copied to clipboard!
!!'0'; // returns true
!!'1'; // returns true
!!'';  // returns false
!!undefined // returns false
booleans.js

This works by first negating the value, which turns it into a boolean, then this boolean is negated again to reflect the true state of the variable.

This solution, however, won't work, if you need to check for the string "true" or "false" specifically, as both will return true. Instead, you can either use JSON.parse or a custom function:

Copied to clipboard! Playground
JSON.parse('true');  // returns true
JSON.parse('false'); // returns false

// To also cater for capitalization, use `toLowerCase`
JSON.parse('True'.toLowerCase());
boolean.js

In case you need to worry about 0 and 1 in string format, you can use a custom function:

Copied to clipboard! Playground
const booleanify = val => {
    if (typeof val === 'string') {
        switch(val.toLowerCase()) {
            case 'true':
            case '1':
                return true;
            case 'false':
            case '0':
                return false;
            default: return !!val;
        }
    } else {
        return !!val;
    }
};

booleanify(0);       // returns false
booleanify('0');     // returns false
booleanify(1);       // returns true
booleanify('1');     // returns true
booleanify(true);    // returns true
booleanify('true');  // returns true
booleanify('True');  // returns true
booleanify(false);   // returns false
booleanify('false'); // returns false
booleanify('False'); // returns false
booleanify('');      // returns false
booleanify('foo');   // returns true
boolean.js
How to Convert Anything to Boolean in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions

Resources:

Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access exclusive interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Remove ads to learn without distractions
Become a Pro

Recommended