Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use the syntax "(function() {...})();"?

Tags:

javascript

My query is used in cases that "(function() {...})();" Given that I am not a plugin. For example "http://piecesofrakesh.blogspot.com/2009/03/downloading-javascript-files-in.html"

(function() {        
  var s = [
    "/javascripts/script1.js",
    "/javascripts/script2.js"
  ];

  var sc = "script", tp = "text/javascript", sa = "setAttribute", doc = document, ua = window.navigator.userAgent;

  for(var i=0, l=s.length; i<l; ++i) {
    if(ua.indexOf("MSIE")!==-1 || ua.indexOf("WebKit")!==-1) {
      doc.writeln("<" + sc + " type=\"" + tp + "\" src=\"" + s[i] + 
          "\" defer></" + sc + ">");
    } else {
      var t=doc.createElement(sc);
      t[sa]("src", s[i]);
      t[sa]("type", tp);
      doc.getElementsByTagName("head")[0].appendChild(t);
    }
  }
})();

Or

var s = [
    "/javascripts/script1.js",
    "/javascripts/script2.js"
];
...

Thank you.

like image 528
andres descalzo Avatar asked Jul 31 '09 13:07

andres descalzo


2 Answers

This is done to avoid naming conflicts.

When you declare a function, that function has its own namespace for variables. By wrapping the code in a function that is immediately invoked, you avoid overwriting global variables with your own values.

In this case s and sc are assigned a value. If you did that at the global scope and other scripts were already using variables with those names for a different purpose, that would cause those other scripts to fail. By introducing the new scope, the identifiers s and sc now refer to different (locally-bound) variables than the variables named s and sc that exist at the global scope.

like image 200
rix0rrr Avatar answered Sep 21 '22 15:09

rix0rrr


Maybe these questions will help you out:

  • Difference between (function(){})(); and function(){}();
  • What do parentheses surrounding a JavaScript object||function||class declaration mean?
  • Javascript: var functionName = function() {} vs function functionName() {}
like image 23
Kip Avatar answered Sep 19 '22 15:09

Kip