4

I came across this form of self invoking function. What is the "!" for?

!function (a) { // something }(1); 
1
  • 2
    Looks like the same purpose as ()'d, to prevent it being parsed as a function declaration. Commented Jan 1, 2013 at 0:33

4 Answers 4

3

By using !, it's evaluating the anonymous function (thereby requiring it to run). Without that, you'd get an error.

And, as others have said, it will invert the result of whatever the function returns, if you're assigning it or evaluating it.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah I see. I usually use (function () {console.log('body');})(). This is just another way of doing this, but saves 1 character.
@Grace-Shao - Yes, that's exactly the case. It has greater significance if you care about what the function returns, but otherwise is used the same.
0

This is to overcome some quirks of JavaScript syntax.

Normally, a function keyword appearing in statement position is interpreted as introducing a function declaration and not as an expression. A function declaration is just that – a declaration, and it cannot have a call operator attached to it. Placing a ! operator before the IIFE forces the function to be considered an expression.

A more straightforward way to resolve this problem would be to wrap the function expression in parentheses, i.e. (function () { /* … */ })(). But ! has one further advantage over the conventional solution: it is more robust against semicolon insertion hazards.

// runs fine var foo = {} !function () { console.log("foo"); }(); // TypeError because of (lack of) ASI var bar = {} (function () { console.log("bar"); })();

Normally a parenthesised expression next to an object literal would be considered a single call expression. But because there is no ! infix operator (and probably never will be – thank this person for it), encountering one between expressions is a syntax error that triggers automatic semicolon insertion before the operator, and the code is read as intended.

Another prefix operator one might as well use to this effect is ~, the bitwise negation operator, or, somewhat more conventionally, the void operator. Personally, I don’t think pandering to semicolon-avoiding code is worth it, but the option is there.

Comments

-1

The not is meaningless unless the functions return value is assigned to something. If assigned, the left hand side will get the not of the result of the self executing function. The result will be the value explicitly returned or the last calculated value in the function.

Comments

-1

if it is returning something, it will just inverse the result:

console.log(!(function(a) { return (a == 1); })(1)); 

will return false. true if you give 0 or anything else.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.