
How to Convert Anything to Boolean in JavaScript
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`
JSON.parse('True'.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!

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

Resources:
π More Webtips
Master the Art of Frontend
Unlimited access to hundred of tutorials
Access to exclusive interactive lessons
Remove ads to learn without distractions