Possible Duplicate:
What is the !! operator in JavaScript?
What does !! (double exclamation point) mean?
I am going through some custom JavaScript code at my workplace and I am not able to understand the following construct.
var myThemeKey = (!!$('row') && $('row').hasClassName('green-theme')) ? 'green' : 'white';
I understand everything on the above line except !!
operator. I assume that it is a NOT
operator and NOT
of NOT
is the original value but why would someone do a NOT
of NOT
?
Can someone please help me understand what is happening on the above line of code?
The double exclamation point, or double bang, converts a truthy or falsy value to “true” or “false”. In other words, it operates exactly like Boolean(value) would.
This punctation emoji of a double exclamation mark features two big red exclamation points that can be used to express surprise, shock, or to really emphasize or drive home a point. This emoji packs a punch and is also reminiscent of comic book actions. Wham!
Use the number of exclamation points that's in your heart. Language is supposed to help you communicate what you mean, so if you need two exclamation points for an extra-emphatic opinion and 27 for an announcement to your brother about your promotion, go for it.
So !! is not an operator, it's just the ! operator twice. It converts a nonboolean to an inverted boolean (for instance, ! 5 would be false, since 5 is a non-false value in JS), then boolean-inverts that so you get the original value as a boolean (so !!
The !!
ensures the resulting type is a boolean (true or false).
javascript:alert("foo")
--> foo
javascript:alert(!"foo")
--> false
javascript:alert(!!"foo")
--> true
javascript:alert(!!null)
--> false
They do this to make sure $('row')
isn't null.
It's shorter to type than $('row') != null ? true : false
.
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