1

I've seen JavaScript that looks like this:

function () {
   // do something
}()

and recently something like this:

(function () {
   // do something
})()

Is there any difference? Both are executed immediately correct?

EDIT:
A note about the first example. The function is being passed to the browser from another application so there was no error from my end. It is throwing an error when run in the browser. After digging in, I've found the application API is passing the function to eval. Both examples above work for me which is why I asked this question.

1.21 gigawatts
  • 12,773
  • 23
  • 85
  • 187
  • 3
    Neither of those are executed immediately. – JJJ Feb 25 '17 at 07:57
  • None of them are executed, because none of them are being called in your samples. You need to provide more context code, yours is ambiguous. Also, this question has been asked and answered here many times. Do a bit of research, please. – Tomalak Feb 25 '17 at 07:58
  • 1
    Remember `function fn(){}()` is incorrect syntax in JS. To execute a function immediately, either use IIFE `(function(){})()` or use function expression – Rajesh Feb 25 '17 at 08:00
  • This might help: http://stackoverflow.com/questions/42431054/javascript-function-behaving-differently/42431236?noredirect=1#comment72008861_42431236 – Rajesh Feb 25 '17 at 08:02
  • The first one is a syntax error, too. – Ry- Feb 25 '17 at 08:05
  • 1
    After your edit, the first example throws a SyntaxError. – dodov Feb 25 '17 at 08:12
  • I can confirm it is throwing an error in the browser console. The code in my first example works when I call it from an external application. I think it works because it's being passed to the eval function. Confirmed. It is passing the function to `eval`. So no syntax error when using that approach. – 1.21 gigawatts Feb 25 '17 at 08:18

1 Answers1

3

Both of the functions won't execute immediately. An immediately invoked function expression has parenthesis at the end of it as well. Like this:

(function () {
    console.log("not hello");
});

(function () {
    console.log("hello");
})();
//^^

The parenthesis enclosing the function turn it to an expression which returns the function itself. Then, you just invoke the returned value (which is the function) with (). Take a look at IIFE.

Edit: After your edit, the first function would just throw SyntaxError: Unexpected token (

Community
  • 1
  • 1
dodov
  • 4,065
  • 3
  • 25
  • 44