69

Possible Duplicate:
return !1 in javascript

In a JavaScript file I had to read today, there was a line where a variable was declared like a factorial, like this :

var myVariable = !1;

and then something similar was used as parameter in a function like this :

return variable.myFunction(!0);

Can anyone explain me what the exclamation mark means in this context and eventually, why this is generally used for (benefits) ?

Thank you in advance !

Community
  • 1
  • 1
m_vdbeek
  • 3,704
  • 7
  • 46
  • 77
  • 7
    It's not a factorial, it's a boolean [negation](http://en.wikipedia.org/wiki/Negation) operator. Turns `true` into `false`, and vice-versa. Probably turns anything else non-zero into zero? – Rob I Jul 18 '12 at 21:32
  • 26
    That's horrible code. Does it throw a [`ViolentPsychopathKnowsWhereYouLiveException`](http://www.codinghorror.com/blog/2008/06/coding-for-violent-psychopaths.html)? – Robert Harvey Jul 18 '12 at 21:35
  • 1
    I laughed uncontrollably upon seeing the title of this question. I had to click it. SMH to whoever codes like this. – Marlon Jul 18 '12 at 21:46
  • 2
    I guess the reason is that the programmer cared a lot about those few bytes that can be saved this way - but this is not a good practice. – kapa Jul 19 '12 at 06:38

1 Answers1

119

The ! is the boolean NOT operator.

NOT (!): toggles a statement from true to false or from false to true.

!0 = true
!1 = false

This is a brilliant introduction to boolean operators and their use in javascript.

Anirudh Ramanathan
  • 46,179
  • 22
  • 132
  • 191