Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double exclamation on a return value in javascript [duplicate]

Tags:

javascript

I'm looking over a book for html 5 and it includes this tid bit of js. What does double exclamation mean?

return ! ! document.createElement('video').canPlayType;
like image 206
steve Avatar asked Dec 22 '10 19:12

steve


People also ask

What does 2 exclamation marks mean in JavaScript?

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.

What does 2 exclamation marks mean in a text?

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.

What does a double mean in JavaScript?

In JavaScript, the double exclamation operator converts an Object to Boolean. This happens such that “falsy” objects become false and “truthy” objects become true.

Should you use double exclamation?

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.


2 Answers

The ! operator negates, and the secondary ! negates the result of the inital negation. This basically typecasts whatever is on the right hand side into a boolean ( true or false ).

!false // true
!!false // false

So if the method is defined then the function which is truthy, will be typecasted into true.

document.createElement('video').canPlayType

So the above returns a function. We don't want a function, we want an explicit boolean, so we negative it twice and since function is not falsy ( 0, null, false, empty string, NaN ) then it returns true for browsers which support this method.

!!document.createElement('video').canPlayType // true

If the method is not supported, the browser will return undefined. !undefined is true, and !true is false, so !!document.createElement('video').LOL will return false

like image 80
meder omuraliev Avatar answered Oct 10 '22 14:10

meder omuraliev


The double exclamation is a JavaScript trick to return true/false regardless of input. In your example, if a browser does not support the video tag, it will return undefined. !undefined is true. So !!undefined is false. If the browser does support video, it will return true. !!true is also true. This saves you from having to handle the case of undefined.

like image 23
James Kovacs Avatar answered Oct 10 '22 14:10

James Kovacs