Contents
A word of introduction
Exclamation mark !
is the logical NOT (!) operator (logical complement, negation) that takes truth to falsity and vice versa. Double exclamation mark !!
is the logical NOT NOT (!!)
In JavaScript, the values false
, null
, undefined
, 0
, -0
, NaN
, and ''
(empty string) are “falsy” values. All other values are “truthy”. See: ECMAScript 2019 7.1.2 ToBoolean.
Below table provides details of how !
and !!
applied to various values:
value | !value | !!value |
---|---|---|
false |
true |
false |
true |
false |
true |
null |
true |
false |
undefined |
true |
false |
0 |
true |
false |
-0 |
true |
false |
1 |
false |
true |
-1 |
false |
true |
NaN |
true |
false |
'' |
true |
false |
example |
false |
true |
Why not to use ! and !!
- It makes the code unreadable. The primary goal of writing the code is to make it human readable so that everyone who’s reading the code can understand it easily.
- Code too long? No need to worry about that as after minification process the code will be smaller anyway. Some part even will be converted to
!
or!!
. - Zero being a falsy value. If data type of the value is meant to be a number, the truthy/falsy evaluation can result in an unexpected outcome. See example:
const example = { exampleA: 0, exampleB: 1 } if (example.exampleA) // The code here is unreachable due to the falsy evaluation console.log('exampleA: ' + example.exampleA); }
A better solution is to use operator
typeof
:const example = { exampleA: 0, exampleB: 1 } if (typeof example.exampleA === 'number') console.log('exampleA: ' + example.exampleA); }
What’s the alternative to single exclamation mark
Simply use typeof
operator to determine the expected type of value instead of implicit conversion to boolean any value. It will make code more readable and predictable.
Caution as null
is an object
in JavaScript.
What’s the alternative to double exclamation mark
Simply use Boolean(value)
instead of !!value
. Read more about Boolean object at Mozilla Developer Network.
Update
Founded quite a nice few comments out there.
Boolean() actually says more about what it does, in plain English.
Keeper the optimization work to the transpiler / minifier. Write readabel Code instead.
I use 10x! eg: !!!!!!!!!!”” just to be on the safe side as a 10x developer
Double negation is great but should be used in moderation. It has a tendency to make code less readable where other alternatives are better. Also, `Boolean`is neat as it can be used as a callback directly. Ex: `[null, undefined, “foo”, “bar”].map(Boolean)`
One place where Boolean() is especially useful is Array.prototype.filter(Boolean()), which strips null and undefined references from an array of objects.
While cleaver, what is the motivation here? Code needs to be clear and concise to tell a story. Clever tricks when used “just because” decreases the code’s usefulness.
Leave a Reply