Welcome to WebmasterWorld Guest from 54.167.76.176

Forum Moderators: open

Message Too Old, No Replies

What is the benefit of wrapping code in function?

     

ocon

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

5+ Year Member Top Contributors Of The Month



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?

g1smd

6:36 am on Oct 9, 2012 (gmt 0)

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



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.

Fotiman

2:04 pm on Oct 9, 2012 (gmt 0)

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




(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). :)
 

Featured Threads

Hot Threads This Week

Hot Threads This Month