JavaScript !! operators

Asked by At

Possible Duplicate:
What is the !! (not not) operator in JavaScript?

I've seen operator ! used like !!. For example


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

If I'm not wrong it's equivalent var filters = typeof document.body.filters != 'undefined'?

Is it a good practice to use !!?

5 Answers

4
alemjerus On Best Solutions

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.

5
jonchang On

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

1
Jan Hančič On

! 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 :)

0
Pavel Radzivilovsky On

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

I think !!(expression) is neat.

1
Tim Down On

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