I was looking for some example code for JS, and I found something that used !function() and I was wondering what exactly is the exclamation for?
5 Answers
! is the boolean not operator. !function() converts the return value of function() to boolean and returns its opposite value
 
    
    - 87,203
- 23
- 98
- 131
If you are substituting the word "function" for the name of a function, it simply means "negate the result of the function".  The ! means not.  So
!true == false
 
    
    - 35,167
- 12
- 80
- 109
functionname is an expression (which presumably evaluates to a function-object) and the result of this evaluation (a function-object) is invoked with () which invokes the function and evaluates to the return value.
Now, this return value (which was the result of an expression) is then negated with the unary ! (not) operator. The rules for ! are !truthy -> false and !falsy -> true, where truthy and falsy are concepts covered "truthy and falsy" in JavaScript.
The example could be written as: !((functioname)()), but that's just silly
Tried this:
var a = !function () {
            alert("notfun");
            return "nottestfun";
        }
alert(a);
It alerts:
false
and nothing else. If you try to run a(), you get a type error:
Uncaught TypeError: Property 'a' of object [object DOMWindow] is not a function
 
    
    - 11,141
- 5
- 43
- 70
- 
                    Because it's not. Remember that `function () {}` (in an expression context, which it is in the in example) is just returning a function-object which is being negated right away! (`var a = !someFunctionObject`) Since an object is a `truthy` value then that is the same as `var a = false` and `false()` is just silly. If you wanted to *evaluate* the function and apply `!` to that... `var a = !(function () {alert("notfun"); return "nottestfun"})(); alert(a)` -- happy coding. – Jan 26 '11 at 03:26
It's a negation. So if function() returns a boolean value, the ! negates it.
Not sure how JS governs naming (the $ is legal), so it could also just be the name of the function :P (I've since checked, and it appears that since ! is an operator, it's not legal, so this is not a possibility).
 
    
    - 75,757
- 21
- 156
- 151
- 
                    1
- 
                    @Reid but oh, they do get used a lot. Javascript is not my specialty. – Rafe Kettler Jan 26 '11 at 03:07
