tags:

views:

215

answers:

5
+5  A: 

It's up to you. All !! does is "cast" its argument to a Boolean.

jonchang
+1  A: 

! negates the result of whatever is on the right. So !! negates the negated value thus ending with whatever was originally on the right.

edit: the above is true if you have boolean values, results may vary for other types ...

edit2 to elaborate some more: !! is a "type cast" operator of sorts. if you have a boolean value on the right then nothing will happen. If you have something other then a boolean value on the right, then the first ! will convert whatever is on the right to the boolean "version" of that value, and the second ! will negate that value. Kinda like saying: return the true value of a non boolean value. Hope that makes sense :)

Jan Hančič
not true. this is so only for booleans, which are not the question's subject.
Pavel Radzivilovsky
It's true regardless of whatever the original type was.
jonchang
That depends on whether whatever was on the right was a boolean value.
Dominic Rodger
No, it doesn't. The result of a `!` or `!!` operation will always be a Boolean, regardless of its original argument.
jonchang
in fact, no matter how many negations you tack together, the result is always boolean.
just somebody
A: 

And what if it is a string with value "undefined"?

I think !!(expression) is neat.

Pavel Radzivilovsky
then the typeof expression will return "string"
just somebody
+3  A: 

It's a common way to convert any return type to boolean (usually to avoid compilation warnings). And second: no, checking if type is "undefined" is mandatory anyway and "!!" can not cover it.

alemjerus
What do you mean by "checking if type is "undefined" is mandatory anyway and "!!" can not cover it."?
Tim Down
"!!" will only allow you to check if operand is zero of any king, but only "typeof()" can tell you if the operand is defined. "!!" for undefined operand will throw a error.
alemjerus
OK, I see what you were getting at now. It's not always true that `!` (and hence `!!`) will throw an error for an undefined operand: for example, `!!window.bananas` will not throw an error while `!!bananas` will. But in general for testing if an object or property is undefined, `typeof` (an operator, not a function, so no parentheses required) is the way to go.
Tim Down
+1  A: 

var filter = !!(document.body.filters);

is NOT equivalent to

var filters = typeof document.body.filters != 'undefined'

!! merely checks if the operand is "truthy", i.e. whether it evaluates to true when used in a boolean expression. It has no relation to typeof. In general with host objects (such as document.body.filters) you are best off using typeof checks. The following article is good reading on this subject: http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting

Tim Down