2

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 !!?

Community
  • 1
  • 1
Tadas Šukys
  • 4,140
  • 4
  • 27
  • 32

5 Answers5

5

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

jonchang
  • 1,434
  • 9
  • 13
4

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
  • 8,023
  • 3
  • 32
  • 40
  • What do you mean by "checking if type is "undefined" is mandatory anyway and "!!" can not cover it."? – Tim Down Dec 14 '09 at 15:02
  • "!!" 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 Dec 14 '09 at 15:20
  • 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 Dec 14 '09 at 16:33
1

! 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č
  • 53,269
  • 16
  • 95
  • 99
1

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
  • 318,141
  • 75
  • 454
  • 536
0

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

I think !!(expression) is neat.

Pavel Radzivilovsky
  • 18,794
  • 5
  • 57
  • 67