What is the !! (not not) operator in JavaScript?
⚡TLDR
!!
is an express route to turning any value into its boolean form: true
if the value is truthy, and false
if it is falsy. This cunning trick serves as JavaScript's equivalent of a boolean conversion shortcut.
Example:
Unveiling the power of the double bang!!
Beyond its basic usage, !!
can pull off some neat tricks in your JavaScript code:
- Feature Detection:
!!
excels in feature detection without the need of extensive error handling.!!(element.dataset)
quickly checks if the dataset property exists. - Code Cleanliness:
!!
helps in making your code more readable and maintainable, especially for conditional assignments.this.isActive = !!user.isActive;
is better thanthis.isActive = user.isActive ? true : false;
- Code Compression: In situations where fewer bytes mean more performance,
!!
stands tall due to its sheer brevity. - Explicit Booleans:
!!
comes handy when calling functions that strictly require boolean arguments. It ensures the argument is always true or false and never a truthy or falsy value.
Remember, !!
and Boolean()
both convert a given value to boolean but the choice between them should consider code readability and maintainability.
The fine print of the double bang operation
The truth about truthy and falsy
JavaScript values may not always simplify to true
or false
. However, using !!
, they will. Let's understand this with the help of some examples:
- Falsy values: These evaluate to
false
via!!
and include0
,-0
,NaN
,null
,undefined
, and the valuefalse
. All known villains of truth. - Truthy values: These convert to
true
and include all non-empty strings, all objects, and all numbers except0
andNaN
. They are the heroes.
Mistakes to avoid with !!
- Mishandling JavaScript can spell disaster. Avoid pitting
!!
against property checks-hasOwnProperty
orin
are the right tools for the task. - Overusing
!!
can lead to redundantly converting variables into booleans when the environment already evaluates truthy or falsy values. - New developers, or those not in the know, might miss the point of
!!
, leading to confusion. So, keeping things transparent and understandable throughBoolean()
can, at times, be preferable.
Optimizing with !!
- The execution time difference between
Boolean()
and!!
is minuscule but worth consideration in high-performance applications where microseconds could make a difference.
Linked
Was this article helpful?