javascriptoperatorsiifeself-invoking-function

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);

Solution

  • 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.