1 - JS Not (!) logical not basics
- The source code examples here are on Github
1.1 - Basic JS Not Example
The operator both converts to boolean and inverts the value that is to the right of the JS Not operator. So for example say I just want a simple function that will return one of two messages depending on the truth value of a single given argument. Where I want to have a message if the value is Not true rather than true, the JS Not operator combined with an if statement and the return keyword can be used to do so.
1.2 - The Double JS Not (!!)
If I just want to convert a value to a boolean type there are other options to that of the JS Not operator. There is of course the Boolean constructor that will just convert a value to what the Boolean value of that value is. The trouble with js not is that it will both convert and invert, which is okay considering that is the expected behavior of it. However if I want to convert and preserve the original truth value with js not, doing so can be easily done by just using the operator twice.
The practice of using the JS Not operator twice is often referred to as Double Not or Not Not.
1.3 - Conversion to Boolean
The JS Not can be used as a way to convert a value to a boolean value. The only thing to remember is that it will do more than just convert, it will convert and invert. So be sure to use two, or one depending on the situation in order to get the desired truth value for the value.
2 - feature testing with the js double not !! operator
The js not operator used twice comes up now and then in many code examples in the wild. In some cases it might seem unnecessary, but it can come in handy when feature testing and I want to return a boolean value rather than another value.
The reason why this works is because calling the js not operator once will convert a value to a boolean, but it will also invert the value of that boolean value. So calling the js not operator once more will then invert it back to its true logical value.
3 - Using js not to make a boolean value bay way of !0 or !1
The number zero will work out to a false boolean value, so using the js not operator will result in a true boolean value. The opposite of this will work out to false by using the js not operator with the number one also on top of this. So then the use of the JS Not operator with the numbers 0 and 1 and be used as a way to make a slightly smaller alternative to that of the true and false literals.
4 - Bitwise not (~)
there is a lot more to cover when it comes to bitwise operators, there is not just the bitwise not, but other operators such as the Bitwise Unsigned Right Shift operator that is used in the above example.
5 - Conclusion