Taming Javascript – a few pointers for developers new to Javascript…

I’ve never had to build any large projects in Javascript until recently, and when the day finally arrived I found myself short of some fairly crucial knowledge.

[Just a quick note to anyone who previously downloaded any of the scripts available on my blog, I recently re-coded all of them and provided documentation for the Lightbox and PictureGallery libraries.]

My biggest mistake was to make assumptions based on my knowledge of other programming languages. During my years as a developer I’ve coded large projects in C/C++, Java, Perl and Python, I’ve also played around with quite a number of other languages including Javacsript. Unfortunately, and to my cost, this gave me a predetermined viewpoint of how Javascript would behave, and well, here are some things to be aware of.

Always, always use var to declare variables

The most important behaviour to be aware of is Javascripts scope handling. The first mistake I made was to ignore the var keyword when declaring variables. If you don’t explicitly declare a variable using var then Javascript will implicitly create it as a global scope variable. The only way to declare a local scope variable is by using var. Of course Most languages have some way of declaring local and global variables, and they differ in how they support it, the real gotcha in Javascript is the lack of block level scope.

Scope is limited and retrospective

Scope applies only globally or within the body of a function, scope does not apply to loops or conditionals. The reason for this limited support (as far as I understand) is that scope is handled in Javascript by two objects one which holds global variables as properties, and one which hold local variables as properties, the later of which is called the call object. The call object is made available to a function at the point that it’s called, and this has interesting results, consider the following code;

var developer_name = "Anthony";
 
function shout_at_developer() {
	alert( developer_name );
	var developer_name = "John";
	alert( developer_name );
}
 
shout_at_developer();

You might expect the code above (as I did) to open an alert box the first time with the message “Anthony” in it, and the second time with “John”, but that’s not what happens. What actually happens is that the first alert box contains the content “Undefined”. Why? Well, because the local variables are stored against the call object, when you declare a variable local to a function it doesn’t matter where you declare it, it will exist within the scope of that function.

So, whenever you declare a variable it’s a good idea in most cases to declare it at the top of the function (since position is irrelevant), and don’t forget that declaring a variable inside a loop or conditional statement will not make it local to that statement, only to the function that statement is defined within.

Browser limitations (or how to kill the web browser)

If your writing anything that could potential loop forever (or a very long time) take care, one of the big issues that I came across is the lack within browser Javascript interpreters to call a sleep (a.k.a delay, wait, etc.) function. Effectively this means all loop operations are CPU intensive since there is no way of handing back CPU time for a period each cycle, this is also a problem in code where functions call themselves to achieve looping or recursive flow.

It’s a good idea to put safe guards in, for example limit a loops iterations using a fail safe count;

var iteration_count = 0;
var max_iteration_count = 1000;
 
while ( true ) {
 
	// Do something...
 
	iteration_count++;
	if ( iteration_count > max_iteration_count ) {
		throw Error( "Too many iterations in loop" );
		break;
	}
}

Browsers vary so testing is crucial

Every web developer is aware of the issues that come with trying to build websites that behave identically across all the leading browsers. Anyone who wants to keep their sanity will use an existing library to minimize how much of this they’ll have to cater for themselves, for example I use the excellent jQuery. But I’m afraid this isn’t going to solve all your problems, there’s quite a few subtle differences between the browsers and since you unlikelybe aware of all them in advance (especially if like me you only use Javascript from time to time) you will need to test thoroughly on any browser you intend to support. Never assume that if your code works in one browser it will work in another, even if the browser only differs by version.

A couple of the most annoying gotchas I came across were specific to Internet Explorer (a.k.a IE), which as standard does not yet provide a useful Javascript debugger (role on verison 8).

IE does not support the following syntax for assigning multiple values returned from a function,

function get_developer_list() {
    return [ "Anthony", "John", "nick" ]
}
var [ developer_a, developer_b, developer_c ] = get_developer_list();

This syntax is supported by both Firefox and Safari, where as IE didn’t provide me with any debug information (not even a warning) for this issue, it just stopped running the code after this point. To support for all of the browsers I assign the values to a list and then assign each item through their index afterwards.

Another small difference in IE’s syntax support, which isn’t really an issue but it did catch me out, is that you can’t leave trailing commas in dictionary declarations, for example;

var developer_data = { "Anthony" : "...", "John" : "...", };

Now, potentially of course you could argue this should throw up an error, but since IE doesn’t care if you do the same thing in lists, and again provides no or only minimal debug information, it can be a frustrating bug to find.

It’s not that bad really…

Despite my frequent jibes and general pessimistic take on having to write Javascript code over the last few weeks, having cast off my assumptions and given the language the time and attention it deserves, actually Javacsript is really quite a nice language (and I’m a bitter and biased developer, or so it would seem).

It’s never going to be my favourite, but at least it does have a rich feature set including good (though yet again quirky) support for object-oriented programming, and a built in regular expression engine.

Advertisements

1 Response to “Taming Javascript – a few pointers for developers new to Javascript…”


  1. 1 webdeveloperboy July 1, 2008 at 1:56 pm

    One day i will understand half of the stuff that your talking about lol, but nice blog none the less…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s





%d bloggers like this: