If it was 1999 and you were telling you’re friends to visit your web site then this post probably wouldn’t fit you.

Luckily for us, it’s not 1999 and calling what I do “building a website” frankly just hurts my feelings (I much prefer web app because web sites were always static pages without much business logic behind it.)

I haven’t lived on this planet long enough to see many programming languages evolve… that is until JavaScript. When I first started building web sites (yes, I called it that back then), the JavaScript I wrote looked like this:

<html>
<head>
<title>Party like it was 1999</title>
<script language="javascript">
<!--
function changeBg(obj, newColor) {
    obj.style.backgroundColor = newColor;
}
-->
</script>
</head>
<body>
<a href="#" onClick="changeBg(this, '#00aaff'); return false;">change background</a>
...

This code makes me cringe! For several reasons. Let me explain…

  1. I never want to see onClick events embedded in your HTML (or presentation markup). Instead, move it to an external file and link it. This goes for the majority of your JavaScript calls, like changeBg() too
  2. You are flooding the global namespace with new functions. Not only is it unmaintainable, it’s also completely devoid of any organization.

The Right Way

Thanks to guys like Paul Buchheit (G-Mail), we have been able to uncover other extremely useful aspects of JavaScript. As JavaScript comes into its own we need to embrace best practices and write beautiful code.

At work, I’ve noticed that while other engineers write great Java code, their JavaScript sometimes looks like a last minute thought. I don’t think this is due to laziness, but rather that they are unaware of the fact that you can apply design patterns to JavaScript just as you would other languages. Usually.

JavaScript Patterns

As I started to write this post I found a bunch of other bloggers already felt the itch and wrote very informative articles on this same topic. So to avoid reinventing the wheel…

Singleton
Module Pattern
Revealing Module Pattern