
How to Convert Anything to Boolean in 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
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());
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

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