Table of Contents
You will be aware of the Logical NOT (!) operator, which is used to negate the expression. In this article, we will see what is !! (not not) operator and its uses.
Truthy and Falsy
Before understanding the not not (!!) operator, we need to understand what is truthy and falsy in JavaScript.
Truthy value is a value that is considered true
in a Boolean context.
That means, if we have an expression as if("John")
or if(1)
then this will evaluate to true
.
Hence, a non-empty string, non-zero number, etc are considered as truthy.
Similarly, falsy is some value that evaluates to false
. Examples are 0
, ''
""
, null
, undefined
etc.
Examples of truthy
The following are the expressions that will evaluate to true
. Hence all the values inside the if conditions are truthy values.
1if (true)2if ({})3if ([])4if (42)5if ("0")6if ("false")7if (new Date())8if (-42)9if (12n)10if (3.14)11if (-3.14)12if (Infinity)13if (-Infinity)
Examples of falsy
Following values are considered as falsy in JavaScript:
false
- 0
- -0
-
'', "", ``
null
undefined
NaN
A complete list can be found here.
The use of !! operator
Let's say we have a function called getProductDetails
which returns the product details when a valid product id is passed.
When an invalid product id is passed it may return an empty string or undefined
.
So the code for processing the product details received as a response would look like this:
1const product = getProductDetails(123)23if (product !== undefined || product !== "") {4 // Process product details5}
With the help of not not operator, we can shorten this as follows:
1const product = getProductDetails(123)23if (!!product) {4 // Process product details5}
!!
is not an operator but two logical NOT (!) operators.
The first one (in the right) will convert the operand (the value under evaluation) to the negated boolean and
the second ! will negate the boolean value again to get the boolean representation of the operand.
That is, !"John"
will be evaluated to false
and !false
will be evaluated to true
.
In case of a falsy value, !0
will be evaluated to true
, and !true
will be false
.
One interesting thing to note is that !!new Boolean(false)
is true
because new Boolean(false)
will create an object,
which is truthy even though it contains a false value.
Do follow me on twitter where I post developer insights more often!
Leave a Comment