2

I am trying to program a simple facebook app. In the code I need, I discovered this:

  // Load the SDK asynchronously
  (function(d){
   var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
   if (d.getElementById(id)) {return;}
   js = d.createElement('script'); js.id = id; js.async = true;
   js.src = "//connect.facebook.net/en_US/all.js";
   ref.parentNode.insertBefore(js, ref);
  }(document));

How come this function is wrapped up in () and (document) is slapped on at the end? I haven't seen this JavaScript sorcery before.

Thanks for any input.

JJJ
  • 32,902
  • 20
  • 89
  • 102
RealityDysfunction
  • 2,609
  • 3
  • 26
  • 53

3 Answers3

7

It's a self executing function that is passing document as an argument.

This could be rewritten as:

var myFunc = function(d) {
    // code here
};

myFunc(document);
Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
1

You use this syntax to create a closure that has the value passed in (document) as the argument for the function parameter. This style is commonly used for things like this:

for (var x = 0; x < 10; x++) {
  (function(y) {
    $.ajax({ params: {value: y}})...
  })(x);
}

What this does is it allows you to force a particular set of values into that context, which is particularly helpful when you want a particular value of a loop to be available to an ajax call made from that iteration.

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
1

JavaScript has a feature known as implied globals. Whenever a name is used, the interpreter walks the scope chain backwards looking for a var statement for that name. If none is found, that variable is assumed to be global. If it’s used in an assignment, the global is created if it doesn’t already exist. This means that using or creating global variables in an anonymous closure is easy. Unfortunately, this leads to hard-to-manage code, as it’s not obvious (to humans) which variables are global in a given file.

Luckily, our anonymous function provides an easy alternative. By passing globals as parameters to our anonymous function, we import them into our code, which is both clearer and faster than implied globals. Here’s an example:

Quoted from: https://stackoverflow.com/a/15777654/3086

Community
  • 1
  • 1
Ignacio
  • 7,947
  • 15
  • 63
  • 74
  • Didn't know if I should mark as duplicate or just answer with a reference. Please edit as needed. – Ignacio Jul 31 '13 at 20:24