One of the best things about reading a book like the jQuery Cookbook, which was written by a collection of jQuery community experts, is that you get see all the cool little tricks that these developers use in their programming. One neat thing that I picked up from James Padolsey was the use of the double not-operator (!!) to convert truthy / falsey values into strict Boolean data types.
To see this in action, take a look at the following demo. I am creating an array of truthy / falsey values and then outputting the values as true Boolean data types:
The single line of importance in the above code is this one:
document.write( !!booly[ i ] );
Here, I am getting the value within the array and then applying the not-operator to it twice. As I mentioned above, the first casts the data type to a true Boolean and then flips it; the second not-operator then re-flips it back to the appropriate Boolean value. When we run the above code, we get the following output:
true : 1
false : 0
true : foo
true : [object HTMLDocument]
Pretty slick. So, why would you want to do this? Well, in jQuery, there are methods that work off of Boolean values (such as jQuery.grep() and jQuery.fn.filter()) and it's nice to have a concise way to perform such conversions. That said, James Padolsey points out in his jQuery Cookbook chapter (page 47):
In fact, the !! is not necessary because jQuery evaluates the return value into a Boolean itself, but keeping it there is still a good idea; anyone looking at your code can be absolutely sure of what you intended (it aids readability).
It might not be necessary, but I like anything that increases readability or creates a more explicit intent.
Want to use code from this post? Check out the license.