What the Heck is !! in JavaScript?

The other day I was rolling through some JavaScript to figure out how a 3rd party library ticked. As I scanned the lines of code I came across a line like the following:

value = !!value;

I have seen this before, but never really thought much of it. But this time was different, I had to know what they were doing. I know leading a JavaScript variable with a ! is a way to test if the variable is true or falsey. By falsey I mean it is either false, null, undefined or the expression resolves to false. If the variable is falsey then !value returns true. So what the heck does !! mean?

I had a suspicion it was simply a way to say "not not" if you will or a double negative. So I decided to step through the code just to make sure and found my guess validated.

In the case of the line I was testing it wanted a true value if the value existed. Of course in JavaScript this means the value could be a Boolean, number, string, array, object or function. In the case of this line it just wanted to set the value of the variable to either true or false. True if the value was something, false otherwise. So by using the shorthand !! the code was in effect replacing something like the following:


     value = true;


That is sort of sneaky, but a great way to reduce code and memory footprint. Hope this helps you write some better JavaScript in the future.

Share This Article With Your Friends!