Welcome to WebmasterWorld Guest from 54.166.158.73

Forum Moderators: open

Message Too Old, No Replies

What is the benefit of wrapping code in function?

     
3:39 am on Oct 9, 2012 (gmt 0)

Full Member

5+ Year Member Top Contributors Of The Month

joined:Sept 30, 2009
posts:227
votes: 1


I have a section of my script that looks like:

(function(){
var g = document.createElement("script");
g.src = "http://www.google-analytics.com/ga.js";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(g, s);
})();

I was curious why this code was wrapped inside a function so I started doing some reading. The way I understand it the wrapper keeps the functions and variables inside the wrapper separate from the rest of the script.

As I'm sure you were able to tell the inside the wrapper is some modified Google Analytics code which loads a secondary, external script.

Would the functions and variables in the secondary script already be kept separate from the first script? In which case I would be able to remove this wrapper as long as I don't use the "g" and "s" variables? Or would the two mix in which case the wrapper would be a good idea to maintain?
6:36 am on Oct 9, 2012 (gmt 0)

Senior Member

WebmasterWorld Senior Member g1smd is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:July 3, 2002
posts:18903
votes: 0


You should write modular code. This allows the code to be re-used in multiple places within a program without duplicating it. It also makes the overall code flow easier to read. Since you can isolate small bits of code it also makes it easier to test it in small chunks.
2:04 pm on Oct 9, 2012 (gmt 0)

Senior Member from US 

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month

joined:Oct 17, 2005
posts: 5003
votes: 20



(function (){
// This code is NOT in the global scope
})();

That is an anonymous function that executes immediately. The vars declared within that will not be global, and generally it's best to avoid creating global variables so you're not dirtying the global namespace (in which case you run the risk of conflicts, etc.).

Would the functions and variables in the secondary script already be kept separate from the first script?

In your example, the g and s variables are only used for the purposes of loading another script. That is, no other code ever references those, so keeping them out of the global scope is a good thing. The script that gets loaded might add more variables to the global scope, or it might do something similar and wrap it's contents in a self executing anonymous function. The only way to tell is to look at the actual script (but ga.js does wrap the contents in an anonymous function). :)
 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members