Lately, I have been focusing a lot on applying separation of concerns to HTML and CSS, and how it fits into the broader topic of web standards. But what about client-side scripting, or web site "behavior"? We need a similar "best practices" methodology applied here, too.
Why "best practices" for JavaScript?
There are many reasons why we need to do this. First of all, in JavaScript, there is more than one way to achieve the same goal. For example, we can use both innerHTML() and DOM manipulation functions to change the content of the HTML page (more on this later). Is one of these ways better than the other? If so, which one, and why?
Second, JavaScript is an extremely forgiving language; in other words, it lacks mechanisms present in other languages that force the developer to write well-structured code. Private attributes, interfaces, and abstract classes are some examples of this. Is there a way to introduce mechanisms in JavaScript to encourage well-structured code? What about design patterns?
Third, the JavaScript client-side code has multiple roles. In a previous post, I have already talked about the importance of JavaScript in dynamic presentation. AJAX has further expanded the role of JavaScript, being additionally responsible for retrieving information from the server. In an earlier post, I talked about how the roles of JavaScript could potentially encompass the control and business logic of a web application. How do we encapsulate these roles?

Figure 1
The Two Keys: The DOM and The XMLHttpRequest Object
In asking why we need a "best practices" approach for JavaScript, we ended up with even more questions. This strongly suggests that we do need an approach to JavaScript coding that gives us some answers. Let's start by looking at a simplified view. Essentially, the purpose of JavaScript can be boiled down to two main parts: communicate with the user, and exchange data with the server.
To accomplish each of these, JavaScript in modern browsers provides us with two "keys": the Document Object Model (DOM) and the XMLHttpRequest object (see figure 1). The DOM has been around for a while; in fact JavaScript would be quite useless without it. Sans-DOM, we'd only be able to communicate with the user through alert, confirm, and prompt dialogs. Not too much fun, right?
Pre-AJAX, the DOM was used for relatively simple tasks, including: basic visual effects such as image swapping, or in some cases, simple client-side validation. With AJAX, we can use JavaScript to retrieve server-side data whenever we want. With all of this data being transferred to/from the server, it's easy to why we're accessing the DOM much more frequently than before AJAX was around.
Taking a break to have a think
I'll leave it at that, for now. In the next few posts, I'll explore both of these "keys" in more detail, while constantly searching for "best practices" approaches to implementing them.
