3

I've seen function(){}() used before, to create a function which then gets called immediately.

So in my node console window I typed the following:

function() { console.log('aoeu') }()
...
...

I was expecting aoeu to be logged as a side effect but it wasn't.

Can anyone please explain why?

PeteGO
  • 5,597
  • 3
  • 39
  • 70
Tim Gregg
  • 53
  • 6
  • You have to wrap the function definition in parens or prepend it with an arithmetic operation or ... to turn it into a function expression. Then you can call it. – Hunan Rostomyan Nov 28 '15 at 21:23
  • 4
    If you really want to know the details of "why", then you have to go read the ECMAScript specification and understand the grammar of the language. The summary is that something that starts with `function()` is a function definition (something that defines a function) and is not an expression that will be immediately evaluated. – jfriend00 Nov 28 '15 at 21:25
  • See [Why do you need to invoke an anonymous function on the same line?](http://stackoverflow.com/questions/1140089/why-do-you-need-to-invoke-an-anonymous-function-on-the-same-line/1140107#1140107) for details on the syntax. – jfriend00 Nov 28 '15 at 21:30
  • `var fun = function(){console.log("aeou")}();` If you make it a function expression rather than a declaration it will work as expected. – bhspencer Nov 28 '15 at 21:35
  • And more info here: [Immediately-Invoked Function Expression (IIFE)](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) – jfriend00 Nov 28 '15 at 21:35
  • @jfriend00 the OP is asking why a function declaration will not be executed with the syntax they have used, they are not asking what an Immediately-Invoked Function Expression is. I believe marking this question as a duplicate was a mistake. – bhspencer Nov 28 '15 at 21:39
  • @bhspencer - That duplicate explains why their syntax doesn't work (because it's a function definition, not a function expression). It also explains what syntax will work to turn it into a function expression. The concept of an IIFE has been written about in hundreds of questions and answers here. There is nothing unique in this question that has not been covered many times before. – jfriend00 Nov 28 '15 at 21:40
  • 1
    @bhspencer - Look in the [duplicate question](http://stackoverflow.com/questions/1634268/explain-javascripts-encapsulated-anonymous-function-syntax) at the point where it asks: ***But I don't understand why this does not work equally as well:***. That's the same question as this one. – jfriend00 Nov 28 '15 at 21:56
  • yes I see that now, thank you. – bhspencer Nov 28 '15 at 22:26

1 Answers1

4

You will get your desired output using

(function(){

  console.log('aoeu');

})();
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59