Stop Using Boolean() in JavaScript
Use the double negation technique instead
Boolean values—named after English mathematician George Boole—are either true or false.
You’ll see the term boolean appear in branches of math such as boolean algebra. In programming, we rely on boolean values for determining the flow of our control structures, such as if statements and while loops.
When we need to convert a value to either true or false, called boolean coercion, JavaScript has the Boolean() built-in function.
If you need a quick, one-time, boolean coercion, there’s a better way.
The Logical Negation Operator
First, we need to introduce the logical negation operator, also known as an exclamation point. The operator’s name is derived from Boolean Algebra’s negation gate and it effectively flips a value from true to false and vice versa.console.log(!true); // false
console.log(!false); // truelet x = 5;
console.log(x != 3); // true
But what happens if ! does not precede a boolean value?
If a value that is not boolean follows the operator, the value will be coerced into a boolean value, then negated.console.log(!0); // true
console.log(!5); // false
console.log(!""); // true
console.log(!null); // true
This gets into a conversation about truthy and falsy values. The tl;dr is that certain values such as empty strings, the integer zero, and null will evaluate to false during boolean coercion. Hence, they are falsy (false-ish) values.
Double Negation Operator?
Now that we know the logical negation operator has the ability to perform boolean coercion, all we need to do is re-negate the boolean value to preserve its original coerced value.console.log(!!5); // true
console.log(!!""); // false
console.log(!!null); // false
Is !! an operator? No. Technically it’s just a double negation operator. But that’s OK because we get a functional replacement for Boolean() with only two characters.
Now, I know that some people will kick and scream about !! being hard to read — I can understand that. But now you have options.
Do you think the double negation technique is easier to read or do you prefer using Boolean()? Share your thoughts and comments below. Thanks for reading!