Oliver
Oliver

Reputation: 3682

javascript function vs. ( function() { ... } ());

I have often see expressions such as:

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

How do I interpret it? syntactically, this alone is a anonymous function definition.

function() {
...
}

what the () after that? and why put it in the enclosing ()?

Thanks

Upvotes: 16

Views: 970

Answers (3)

mikemaccana
mikemaccana

Reputation: 123610

This is an old question, but my build is taking a while and I think I can provide a better answer:

Short answer: the () runs the function you just made.

Functions

function() {
  const x = 1;
  ...
}

This is a regular anonymous function as you mentioned

Immediately Invoked Function Expressions

   (function () {
     const x = 1;
     ...
   }());

This:

  • Creates an anonymous function just like the above
  • Runs the function ...()

It's similar to making an array and then running a method on it ['one', 'two'].split(). You're defining something, then doing something with the thing you've just defined.

Why use IIFEs in 2024?

You may see old codebases that use IIFEs to create an async scope to run async/await code, but there's no reason to do this anymore. You can now use top level await in all supported versions of node.js. So you can just await promises.readFile() in a JS file and it just works.

Upvotes: -1

jamesmortensen
jamesmortensen

Reputation: 34078

The area where I most often find this useful is in callback functions. This notation can also used in cases where you need to include a variable in a callback function, but you need the variable state to not be affected by what goes on outside the function.

 var someVal = 1;

 setTimeout( (function(one) {
      return function() {
           alert(one);  // alerts a 1 even 10 seconds after someVal++;
      }
 })(someVal), 10000);

 someVal++;  // the value in the setTimeout will remain the same as it is locked inside.

In this context, setTimeout takes a function that takes no arguments. So the question of how to pass in a value to that function is answered by creating a function that takes one argument that returns a function that takes 0 arguments.

I suggest anyone wanting to learn more about the power of this notation to play around with it in the Firebug JavaScript console. Once you wrap your head around this concept, you'll start to see areas where this powerful concept can be used.

Upvotes: 2

user113716
user113716

Reputation: 322592

Exactly the same, except that it is being invoked immediately after being converted into a function expression.

// v-----first set of parentheses makes the function an expression
   (function () {
       var x = 1;
       ...
   }());
//  ^-----this set is used to invoke the function

Same as if you did:

   var myfunc = function () {
       var x = 1;
       ...
   };
   myfunc();

or (similar) this:

   var returnValue = function () {
       var x = 1;
       ...
   }();

Get rid of the names, move the parentheses around, and you can see they're not that different.

Upvotes: 24

Related Questions