2

I know what auto-running functions are, I use them very often in both Node.js and simple JavaScript. But I still don't understand something.

I kind of know why the following works

(function () {/* Stuff */})();

But I seriously have no idea why the following works...

(function () {/* Stuff */}());

...while the following doesn't...

function () {/* Stuff */}();

...but this also works...

!function () {/* Stuff */}(); // The "!" can be any valid expression

Can I get a detailed explanation?

J. Orbe
  • 143
  • 1
  • 4
Bálint
  • 3,717
  • 2
  • 13
  • 27
  • 2
    Duplicate of [!function(){ }() vs (function(){ })()](http://stackoverflow.com/q/8305915/218196), [What does the exclamation mark do before the function?](http://stackoverflow.com/q/3755606/218196), [Javascript anonymous function call](http://stackoverflow.com/q/9091289/218196), [Explain JavaScript's encapsulated anonymous function syntax](http://stackoverflow.com/q/1634268/218196) and others. – Felix Kling Oct 24 '16 at 19:43
  • *"The "!" can be any valid expression"* That's incorrect. `!` needs to be a unary operator. – Felix Kling Oct 24 '16 at 19:53

1 Answers1

-1

If it is javascript

(function () {console.log("hi");})();

This is an Immediately invocable function expression, which mean definition followed by invocation, so as it is getting called immediately it works

function () {console.log("hi")}();

This will throw an error ,because definition is followed by braces,if you want to invoke it make it an IIFE

!function () {console.log("hi")}();

This is because, if you put a unary operator before the function declaration, you need not add closing braces, and it chops off one character of the code.

Hope it helps

Geeky
  • 6,986
  • 2
  • 19
  • 48