This is the long over-due follow-up article to JavaScript – Much more than Java’s Mini-Me which I want to get published now because I’ve just started another JS article that I think needs to come after this article. I want to finish evangelizing the good things about the JS language before I take a look at JS’s dark under-belly. The next article has the working title JavaScript and AJAX on the Web – a Liability? and should be out within a week (at least that’s the plan).

In my previous JS article I discussed fundamental language features that JS has that give it the ability to do things many other languages just can’t. These features give the programmer extra tools that the common high-level languages like Java just don’t have. In this article I won’t be looking at anything as earth-shattering as that, I’ll just be looking at some nice features JS has that tend to get over-looked by JS programmers.

[tags]JavaScript, JS[/tags]

RE Literals

Regular expressions provide the programmer with a very powerful tool, especially when dealing with string manipulation and data validation. In Java you do have RE support but not RE literals so you have to represent the pattern for your RE as a String. This sounds OK but it has one major problem, some characters need to be escaped twice, once for the String, and once for the RE. This results in some really hard to read and very confusing code. By having an RE literal JS avoids that mess. Those of you who program in Perl will of course point out that this is nothing new, it isn’t but good RE support is a something I weight very highly when choosing a language to use. PHP and Java both fall down on this one, Perl and JS both get full marks here (JS took it’s syntax straight from Perl).

To illustrate this point, here is a simple example. Below is a simple Java function to escape strings for use in an SQL query:

public static String toSqlEscaped(String raw) {
    String ans = raw;
    //first escape all backslashes
    ans = ans.replaceAll("\\\\", "\\\\\\\\");
    //then escape all single quotations
    ans = ans.replaceAll("\\'", "\\\\'");
    return ans;
  }

Messy isn’t it! The first RE looks like it is replacing two backslashes with four but it is in fact replacing one backslash with two. The reason it’s so messy is that both the pattern and the replacement are REs so backslash has to be escaped twice in both. Head wrecking stuff! Anyhow, here is the same as a JS function:

function sqlEscape(raw){
  var ans = raw
  ans = ans.replace(/\\/g, "\\\\");
  ans = ans.replace(/'/g, "\\'");
  return ans;
}

Object Literals & Object Loops

While I’m talking about literals I may as well mention a JS feature that is very little known but none-the-less cool. You can create an object without creating a class, and in just one line! Granted, it will be an object without any functions, but you can add them in at any stage should you need them (as described in my previous JS article). So, how, and what has this to do with literals? Well, believe it or not, there is an Object Literal in JS! To create an object with the properties name, address & serialNumber you’d do something like:

//create an object with a literal
var myObject = {name: 'Bart Busschots', address: 'www.bartbusschots.ie', serialNumber: '007'};

//mess with it
myObject.name += ' the third';

Another thing you can do with objects really easily in JS is loop through all attributes of any object. This can be done in Java using reflection but that’s not for the faint-hearted. Take a look at the following function to print all data in any object:

function printObject(o){
  for(var attrib in o){
    window.alert(attrib + " = " + o[attrib]);
  }
}

Did you know JS has Hash Tables?

If you’re a Perl programmer you soon come to rely on the ability to index compound variables by more than just number. You like the idea of being able to store the temperature of each day of the week in a single variable indexed by the days of the week rather than by the numbers 0 to 6. The ability to index by more than just numbers allows for the creation of better and simpler data structures. Java Programmers have tended to minimize their use of hash tables because these are far from simple in pre version 1.5 implementations of Java. This was because their use led to a lot of code over-head for boxing and un-boxing variables and the more you used them the more potential you had for pushing errors that should be compile-time errors over to run-time exceptions such as the dreaded ClassCastException.

In JS you’ve been using hashes for years and you’ve probably never realized it! An Array object in JS is in fact a hash table in disguise! You can index a JS array with strings or numbers and JS won’t care. Just have a look at the sample code below:

var TZOffset = new Array();
TZOffset['GMT'] = 0;
TZOffset['BST'] = 1;
TZOffset['CET'] = -1;

var TZ = window.prompt("please enter your time zone code e.g. GMT", "");
TZ = TZ.toUpperCase();
var ans = "unknow";
if(TZOffset[TZ] != undefined){
  ans = TZOffset[TZ];
}
window.alert("The off-set from UTC of the time-zone " + TZ + " is " + ans);

Did you know JS does exception handling?

With the exception (no pun intended I swear) of people who do a lot of AJAX programming most people aren’t aware that JS has Java-like exception handling capabilities. The syntax is pretty much straight from Java as shown by this example.

var x = 10;
try{
  x.dflkgjdflkgjdflgkjdg();
}catch(e){
  window.alert(e);
}

This will throw an exception because the function dflkgjdflkgjdflgkjdg does not exist on the variable x.