Friday, March 09, 2007

Playing with Javascript

I've pasted an early version of a recursive function to walk the DOM from a particular node in Javascript. If you run the code though.. your browser will hang as it goes into a recursive loop. So whats wrong with the code?

<html>
<head>
<script type="text/javascript" language="javascript">
function walk(node) {
if (node) {
//do something with node
for (i=0; i<node.childNodes.length; i++) {
walk(node.childNodes[i]);
}
}
}
</script>
</head>
<body onLoad="walk(document.body)">
<a href="http://www.parivartana.org">parivartana.org</a>
</body>
</html>

The variable i in the for loop should be declared as 'var i' to fix the behaviour. Thats when I realised that I should not really code in Javascript assuming that it is a subset of Java. (But being as lazy as I am never really studied the language).

Then I came across some fantastic videos on Javscript by Douglas Crockford at the YUI theatre which is a part of the Yahoo Javascript library YUI. Some of the features of the language are explained really well. Some key features are Objects as containers, Prototypal Inheritance and Lamda. He also explains some browser and Javascript quirks.

Now I am wondering if Javascript should be a part of my resume!

One of his recommendations is to favour minification ie removing of whitespace to reduce download size versus obfuscation. Google actually always heavily obfuscate their Javascript. Also as part of the Google Web Toolkit, the deployable code is also obfuscated. So thats a debateable topic. Time to read some GWT generated code then.

No comments: