4 ms·
Excuse my ignorance, what's the !! for?
by mbenjaminsmith 16y ago
Excuse my ignorance, what's the !! for?
- enqk 16y agoconverts a value that evaluates to false, to an actual false boolean.
- donalm 16y agoIts two negation operators. The first returns false is the object exists and true if it doesn't and the second flips that around. So you get true if the object exists and false otherwise.
- uggedal 16y agoDouble negation is used for explicit boolean conversion, i.e.: !!0 -> false !!1 -> true !!"" -> false !!"s" -> true !!null -> false !!undefined -> false
- rlivsey 16y agoIt makes sure that it returns a boolean value as opposed to something truthy/falsy which could lead to oddness if you try and directly compare it with a boolean value. According to the spec, media.canPlayType returns either "", "maybe" or "probably". An empty string "" is falsy in Javascript and a non-empty string is truthy, but if you try and compare them directly with booleans then you can get some odd behaviour: if ("yes"){ // true } if ("yes" == true){ // false } if ("yes" === true){ // false } if (""){ // false } if ("" == false){ // true } if ("" === false){ // false } I personally prefer to make sure that any function which you're expecting the return value to be used as a boolean actually returns a boolean value. I know there are many people out there with a dislike of !! though.
- gjm11 16y agoCanonicalization, so that e.g. null and undefined turn into false and ordinary values (e.g. functions, arrays, numbers, objects) turn into true. Try putting things like these into the address bar of your browser: javascript:alert(!!null) javascript:alert(!!undefined) javascript:alert(!!{}) javascript:alert(!!Math.floor)
- mbenjaminsmith 16y agoAhh, thanks for that. Coercion to boolean.
- kaptain 16y agoIt's to magnify the emotion expressed. In the olden days, before emoticons, people used a larger vocabulary to express themselves, but often times that failed to express the magnitude of their feelings. They used !! for that purpose. Of course, today we see the abuse of the !! quite rampant. I LOVE YOUR HTML5!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! is an example of this. Note that this is a post-fix operator.
- j79 16y agoHah! I am guilty of over using exclamation marks in posts/texts. I eventually found myself re-reading messages and stripping them out! Unfortunately, nowadays, it's emoticons I overuse. :)
- yason 16y agoThe others already answered this but I suppose writing return Boolean(x) instead of return !!x would be much clearer.