I came across this form of self invoking function. What is the "!" for?
!function (a) { // something }(1); I came across this form of self invoking function. What is the "!" for?
!function (a) { // something }(1); 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.
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.