0

I'm trying to understand the difference between :

var x = function () {  ....}

(function () { ....} ) ();

I get it that the first function will put the results on x.

that and when exactly the second one will be fired? and why do i need the (); at the end?

p.s.w.g
  • 136,020
  • 27
  • 262
  • 299
USer22999299
  • 4,180
  • 7
  • 36
  • 66
  • http://stackoverflow.com/questions/13167554/function-returning-a-function-to-a-variable-why-does-it-need-the-extra-set-of ? –  Nov 08 '13 at 06:18
  • 2
    The first one doesn't put the results in `x`, it sets `x` to the function. – Barmar Nov 08 '13 at 06:19
  • 2
    `(function() {...})();` is the same as `function foo() {....}; (foo)();`. – Felix Kling Nov 08 '13 at 06:21
  • @FelixKling:thats almost the same..if u leave out scoping features that IIFE involves – HIRA THAKUR Nov 08 '13 at 06:22
  • @Onaseriousnote: `foo` will have the same scope behaviour as the anonymous function. Or do you mean that the anonymous function is not accessible anywhere else? That's of course a difference. – Felix Kling Nov 08 '13 at 06:24
  • why is it so important to use iife..i have seen people using this when the job can be done using simple function? – HIRA THAKUR Nov 08 '13 at 06:33

1 Answers1

1

This is an example of the Immediately-invoked function expression.

The function is executed immediately because () is how JavaScript calls functions. The syntax might be confuse you, because the function does not have a name, but ( function(){} )() just immediately calls the function with no arguments.

Brian
  • 6,010
  • 3
  • 20
  • 38