The first time I saw an expression using the !!
I had no idea what that piece of code was supposed to be doing there. If youβre just getting started with Javascript, looking at something like value = !!value
might seem like a strange sorcery.
Trying to understand the definition behind this could probably not be that straightforward to everybody the first time so, hereβs a short and quick way to explain what is the !!
operator:
The !!
(not not) operator in Javascript is just really a simple way to convert any value to boolean.
That's it, that's the quick and direct answer for it. If you want to go a bit further:
The single !
converts a value to its truthy or falsy value, which is technically a boolean, but, if you need a real boolean representation of a value for your expression, you must convert it to a real boolean using an extra !
.
But wait, what is that truthy, falsy thing?
A quick way to explain truthy and falsy is that all values are considered true
(truthy) unless they are false
(falsy) values by nature.
These falsy values are: undefined
, null
, NaN
, 0
, ""
(empty string), false
(duh, of course).
Wanna try it yourself? Go to your console and evaluate the following expressions:
!![]
!!{}
!!12
!!0
This is a definition commonly asked nowadays in interviews so make sure to keep it present.
Thank you for reading! And if you liked this article drop a β€οΈ
Top comments (0)