How to Convert Anything to Boolean in JavaScript

How to Convert Anything to Boolean in JavaScript

Ferenc Almasi β€’ πŸ”„ 2020 September 28 β€’ πŸ“– 2 min read

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

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

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:

JSON.parse('true');  // returns true
JSON.parse('false'); // returns false

// To also cater for capitalization, use `toLowerCase`
Copied to clipboard!

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

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
Copied to clipboard!
How to Convert Anything to Boolean in JavaScript
If you would like to see more Webtips, follow @flowforfrank

50 JavaScript Interview Questions
Looking to improve your skills? Check out our interactive course to master JavaScript from start to finish.
Master JavaScript


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