Subtitle: Or At Least, New Best Practices for Me

Now let me be honest: I’ve never been a fan of front end development. HTML sucked, Javascript wasn’t close to my favorite (I’d much rather code up some assembly than touch Javascript) and their interaction with each other was dirty, at best. With the dawn of HTML5, I’ve become interested in HTML again and viewing (or, trying to view) the Javascript source of the very prominent websites got me interested in Javascript. The real turning point for me was watching Paul Irish’s 10 Things I Learned from the jQuery Source. That video, really, has turned me around on the power of Javascript.

Here’s what I’ve got out of it so far:


        <script src="test.js" type="text/javascript"></script>
        <script src="test.js" type="text/javascript"></script>


    var TEST = window.TEST || {test: 0};

    window['TEST'] = TEST;

Now what am I going on about?

Now after some research, this looks to be the “cool” way to do Javascript these days. I kind of like it. I wrote this up due to line #1 in test.js as a test. Many times I’ve seen people write

var OBJ = OBJ || {};

Now the cool part about this is including the file multiple times by mistake. That line tries to guarantee that regardless of how many times you try to include the Javascript on the page, only one object is created. The problem is, without checking window.OBJ, the reference will be lost and overwritten. The two test files I’ve pasted tests this. The HTML includes the Javascript twice. The EXPECTED behavior is to include the file once, have the alert show you 1 include the file again then the alert should show you 2. Leaving off the window. part of window.OBJ alerts you with 1 both times. Probably not what you want. Anyway I thought it was just an interesting test to confirm what I thought was correct. Also, I am asking for input. Is this correct? Is there a fancier way to go about doing this? Any references out there that will help me learn the latest and greatest way to use Javascript?