In some code I have seen a double negation !!
in front of a variable, for example:
{ token: !!localStorage.getItem('token') }
I understand that a negation is used !
to perform a logical negation on an expression.
But a double negation converts it back to the state as it was originally received, for example:
var token = true;
console.log( token ); // true
console.log( !token ); // false
console.log( !!token ); // true
For what and why is this technique used in JavaScript?
Surely now you will be more confused, but let's see some examples:
Perhaps now the first paragraph is better understood with the examples:
Double negation is mostly used
!!
to force the conversion of the type, it is similar if we want to compare the type of the value with the equality==
operator as well, we would have to use the strictly equal===
operator .An example that can also be seen in real codes:
In the example we are comparing the value with
true
(boolean), if we would not use the double negation!!
it would always return a false.Other uses would also be to obfuscate the code, example:
They also say it's faster if we use double negation but judge for yourself, I've created one
Benchmark
in jsPerf - See SpeedTest ...Sources and where you can see more examples and explanations: