Grace Huang
Grace Huang

Reputation: 5709

Why prefix an IIFE by a negation operator (exclamation mark)?

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

!function (a) {
    // something
}(1);

Upvotes: 4

Views: 129

Answers (4)

dumbass
dumbass

Reputation: 27239

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.

Upvotes: 0

kennypu
kennypu

Reputation: 6061

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.

Upvotes: -1

Apropos
Apropos

Reputation: 516

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.

Upvotes: 3

doles
doles

Reputation: 556

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.

Upvotes: -1

Related Questions