I can understand cases when you will want to convert an object value to a boolean and save it in a variable. However, I came across the following code in a jQuery template and was wondering if the !! (double exclamation operators) is even necessary.
{{if !!sectionId}}
// do something...
{{/if}}
I am assuming that it is not since Javascript will automatically evaluate the expression following the if as boolean. Therefore, you could just write:
{{if sectionId}}
// do something...
{{/if}}
Am I right in my assumption?
There is no !! operator in JavaScript. There's just !. What you're seeing is a doubled application of that single operator.
A single application of ! will return a boolean by evaluating the "truthiness" of its argument, giving the boolean inverse of that. The second ! therefore gives the boolean inverse of that value, which is thus the boolean "truthiness" of the original value.
Personally I wouldn't use it in a simple if statement as in your example, but it's handy for APIs that might explicitly check for a boolean-typed parameter:
someAPI( !! someExpression );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With