Question

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

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

I don't know whether there is an existing question or not. Sorry if this is a dup.

Was it helpful?

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.

OTHER TIPS

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top