Friday, May 23, 2008

Learning JavaScript (finally)

I'll be honest. Until recently, I haven't really used much JavaScript in the Web Applications that I've built. I've usually preferred to take the post back hit and perform the necessary functions server-side, instead of trying to craft the right JavaScript routines that work across all browsers. In my new job however, we use a fairly large amount of JavaScript to deliver rich functionality directly on the page client-side. Time to get me some learn'n on JavaScript.

Because I had stayed away from JavaScript for so long, I never really got a good feel for it. I could read an existing script and determine what it was doing with little effort, but I would be hard pressed to write my own script that did anything beyond the basics. One of the reasons for this was that any resource I found on JavaScript never spelled out how the language is composited within a Web Browser.

Since JavaScript is a dynamic language, it can be implemented wherever you like; not just within a Web Browser. However, when JavaScript is implemented in a Web Browser, additional methods and properties are merged in from 2 other sources: The Document Object Model (DOM) and HTML.

The DOM is a hierarchical structure of all of the elements making up a document. Every element has parent (except root), 0 or more children, and 0 or more siblings (elements at the same level). Any JavaScript variable that references an element within the web page inherits the methods and properties supplied by the DOM based on the type of element it is, in addition to the standard methods and properties defined for JavaScript objects.

You will also inherit properties based on the HTML type the element represents. For instance, if the JavaScript variable is currently pointing to an element, then the variable will have properties that match what is available for an image, such as Alt, Src, Height, Width, etc.

Thus, any given variable in JavaScript can have methods and properties composed from 3 possible sources: core JavaScript, the DOM, and HTML. This may seem trivial to most people who have been writing JavaScript for several years, but to someone who has avoided the language for a while, this can be a source of confusion. Especially since most books seem to gloss over this composition behavior. Once you are aware of this, writing JavaScript becomes a lot easier.

In order to grasp the full capability of JavaScript within the context of a Web Browser, I would suggest buying at least 2 books: One on JavaScript (the language), and another on the Document Object Model (DOM). If you are lucky, you can find a book that does a good job incorporating all of these aspects in one place.