1

Can someone explain to me what this syntax is doing?

(function(star){
    //do something
})(star || (star = {}));
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
Jimmy Vo
  • 124
  • 2
  • 11
  • 1
    Possible duplicate of [Explain JavaScript's encapsulated anonymous function syntax](http://stackoverflow.com/questions/1634268/explain-javascripts-encapsulated-anonymous-function-syntax) – Pat Aug 29 '16 at 19:56
  • It is an immediately invoked function. http://benalman.com/news/2010/11/immediately-invoked-function-expression/ – TheDude Aug 29 '16 at 19:56
  • Possible duplicate of [What is the (function() { } )() construct in JavaScript?](http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript) – user2864740 Aug 29 '16 at 20:34

4 Answers4

5

It is called an IIFE (Immediately-invoked function expression) that is run as soon as it is loaded. It is used to avoid polluting the global namespace. That is, the variables in the function are not in the global scope, so they are executed then gone (save for anything that would still have a valid reference)

James Ralston
  • 1,170
  • 8
  • 11
3

It's declaring an anonymous function and immediately invoking it with the expression star || (star = {}), which essentially initializes star to an empty object if necessary, then passes it as an argument.

shmosel
  • 49,289
  • 6
  • 73
  • 138
2

The fact that the line comment comments out the entire second half of the code makes this invalid JavaScript syntax.


Assuming that the function was formatted like this:

(function(star){
    //do something
})(star || (star = {}));

Here, you are defining an anonymous function and invoke it immediately. This has the benefit that //do something is executed in its own function scope, preventing variables from being leaked into the global state. This pattern is called immediately-invoked function expression (IIFE).


star || (star = {}) defaults star to an empty object in case it is falsey, which happens e.g. when it is not set.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

This is an anonymous selfcalling function. Usually you do:

function a(b,c){
//execute
}
a(1,2);

But then others can execute this function, and if you want to put it into a variable its a bit long:

function a(b,c){
return b+c;
}
d=a(1,2);

With the selfcalling function, this is much easier:

d=(function(b,c){return b+c;})(1,2);

It has the following syntax:

(anonymous function to call)(passed variables)
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151