Hidden JavaScript

Filed Under Computers, Software Development, Web Development on October 27, 2006 at 6:15 pm

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.

Technorati 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:

  1. public static String toSqlEscaped(String raw) {
  2.     String ans = raw;
  3.     //first escape all backslashes
  4.     ans = ans.replaceAll("\\\\", "\\\\\\\\");
  5.     //then escape all single quotations
  6.     ans = ans.replaceAll("\\'", "\\\\'");
  7.     return ans;
  8.   }

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:

  1. function sqlEscape(raw){
  2.   var ans = raw
  3.   ans = ans.replace(/\\/g, "\\\\");
  4.   ans = ans.replace(/'/g, "\\'");
  5.   return ans;
  6. }

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:

  1. //create an object with a literal
  2. var myObject = {name: 'Bart Busschots', address: 'www.bartbusschots.ie', serialNumber: '007'};
  3.  
  4. //mess with it
  5. 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:

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

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:

  1. var TZOffset = new Array();
  2. TZOffset['GMT'] = 0;
  3. TZOffset['BST'] = 1;
  4. TZOffset['CET'] = -1;
  5.  
  6. var TZ = window.prompt("please enter your time zone code e.g. GMT", "");
  7. TZ = TZ.toUpperCase();
  8. var ans = "unknow";
  9. if(TZOffset[TZ] != undefined){
  10.   ans = TZOffset[TZ];
  11. }
  12. 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.

  1. var x = 10;
  2. try{
  3.   x.dflkgjdflkgjdflgkjdg();
  4. }catch(e){
  5.   window.alert(e);
  6. }

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

Comments

2 Responses to “Hidden JavaScript”

  1. Des Traynor on October 27th, 2006 9:49 pm

    Very good post Bart, nice one.

  2. Are the Days of JS and AJAX numbered? : Bart Busschots on February 15th, 2007 10:04 pm

    [...] A couple of months back I wrote two articles singing JavaScript’s praises from a programmer’s point of view (JavaScript – Much more than Java’s Mini-Me & Hidden JavaScript). In the last one I hinted that there would be a follow-on article showing a darker side to JS. This is that article, just a few months later than I’d planned. Unlike the previous two articles this one is not really aimed at programmers, it’s aimed at anyone who surfs the web. [...]

Leave a Reply




Before you post a comment please remember that commenting on my blog is a privilege not a right. I won't approve comments that are obscene, offensive or insulting. For more info please read this post.

Subscribe without commenting