Wednesday, March 28, 2012

JavaScript Function Spaghetti Code

In this post we will have a look at the spaghetti code created by functions and how to avoid them. First lets quickly go through why this is a cause of concern.

Problems with Function Spaghetti Code

  • Variables/ functions are added to the global scope

  • The code is not modular

  • There's potential for duplicate function names

  • Difficult to maintain

  • No namespace sense.

Let's take for example the following set of functions and check whats the issue with them.
// file1.js

function saveState(obj) {
    // write code here to saveState of some object
    alert('file1 saveState');

// file2.js (remote team or some third party scripts)
function saveState(obj, obj2) {
     // further code...
    alert('file2 saveState");

Now the problem here is if your application is using saveState() then the execution of saveState() which one to call is determined by the script loading.  The later script overrides same functions already defined by earlier script.
For e.g.

If this script is references as
<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>

Then the function defined in file2.js will be overriding the one defined in file1.js. If you change the order the order of overriding changes. So, you can see this is a cause of concern if you have a n application which depends of javascripts both internal and from third party. One way to solve this problem is with closures.

Closure inner function always has access to the vars and parameters of its outer function, even after the outer function has returned. ~ Douglas Crockford
In JavaScript yo can nest function and the nested function has access to all the variables and functions defined by its parent. This seems very simple and straightforward, but this is a very complex concept under the hood. Its like a function still holds the variables around its environment even after the function seems out of scope. Let us quickly go through an example.

// The getDate() function returns a nested function which refers the 'date' variable defined 
// by outer function getDate()
function getDate() {
   var date = new Date();    // This variable stays around even after function returns

   // nested function
   return function () {
      return date.getMilliseconds();

Now if you call this function as shown below, you will see that the inner function holds on 
the the date variable.

// Once getDate() is executed the variable date should be out of scope and it is, but since 
// the inner function
// referenes date, this value is available to the inner function.
var dt = getDate();


The output of the above alert will be the same value of date.getMilliseconds();

Let's take another look at closure and use a module kind of pattern..

var MyDate = function () {
    var date = new Date();
    var getMilliSeconds = function () {
        return date.getMilliseconds();

var dt = new MyDate();

alert(dt.getMilliSeconds());  // This will throw error as getMilliSeconds is not accessible.

Make the following changes
var MyDate = function () {
    var date = new Date();
    var getMilliSeconds = function () {
        return date.getMilliseconds();
    return {
        getMs : getMilliSeconds

What you are doing above is encapsulating all your logic in a namespace, in this case MyDate, and only
returning public methods to the outside world as an object literal.

You can use this as shown below..

var dt = new MyDate();
alert(dt.getMs());  // This should work.

The above construct is very similar to "The Revealing Module Pattern", which we will cover in
subsequent posts.

Now let's solve the original problem of saveState.

function App() {
    var save = function (o) {
        // write code to save state here..
        // you have acces to 'o' here...
    return {
        saveState: save

var app = new App();

app.saveState({ name: "rajesh"});

Your application can use this as follows, without worrying about other saveStates floating around...

var app = new App();
app.saveState({ name: "rajesh"});

To conclude, we had look at why function spaghetti coding is bad and how to avoid this by using closure and module pattern.

In subsequent post we will look at how to create namespace and dig into deeper of the module pattern.

Hopefully you will find this useful.


gas razor scooter said...

Nice blog here! Also your web site loads up fast!
What host are you using? Can I get your affiliate link to your host?
I wish my website loaded up as quickly as yours lol

brooks running shoes said...

Thank you for the auspicious writeup. It in fact was a amusement account it.

Look advanced to more added agreeable from you! However, how can we communicate?

Viagra online without prescription said...

Highly descriptive post, I enjoyed that a lot. Will there be a part 2?

seo for small companies said...

Your mode of telling all in this post is really nice,
every one be capable of effortlessly know it, Thanks a lot.

article spinning tips said...

This piece of writing gives clear idea for the new visitors of blogging, that actually how to do blogging.

Singapore Web Design, Singapore SEO, Singapore Internet Marketing said...

Thank you a bunch for sharing this with all folks you actually recognise what you are talking about! Bookmarked. Kindly additionally talk over with my web site =). We can have a link exchange contract between us

Singapore Web Design, Singapore SEO, Singapore Internet Marketing said...

hello!,I really like your writing very much! proportion we be in contact extra about your post on AOL? I require an expert in this house to solve my problem. May be that is you! Taking a look forward to peer you.

ehzilqxnx said...

tvvcmJ tvsmghqhnbcb, [url=]avrznpcyxcuv[/url], [link=]zyruijlomkem[/link],

Leeboxz2 said...


Great blog post, saw on...