jMar"s Blog DevSmash Developer Portal

Tuesday, March 18, 2008

Web 2.0, Meet JavaScript 2.0

Well I suppose it's an undeniable fact about us programmer-types - every now and then we just can't help but get excited about something really nerdy. For me right now, that is definitely JavaScript 2.0. I was just taking a look at the proposed specifications and I am really, truly excited about what we have coming.

I suppose it's important to note that these new features are tentative. The specifications documentation for JavaScript 2.0, ECMAScript Edition 4, is currently being developed by TC39. Although it is still a work in progress, an overview of what has currently been proposed can be found here (PDF). As the team expects to have completed the specifications by late fall of this year, we can expect that most of these awesome improvements will remain in the final version.

So without further delay, here's just a few of the many, many upgrades coming JavaScript 2.0's way:


Had to start with this one - it's so big it had to be first. Introducing actual classes and interfaces into the language is likely the most radical change that will come with JavaScript 2.0. Technically speaking, OOP will be nothing new for JavaScript. JavaScript already has objects and even offers full support for inheritance through the prototype chain - however, prototypal inheritance in JavaScript is tricky business and can often produce unexpected results (especially for those accustomed to classical inheritance in languages such as Java and C#).

Not only is JavaScript introducing classes into the language, is is also doing away with primitives altogether. Null and undefined will be the only not true objects in JavaScript 2.0. Duly, classes such as boolean and string will provide wrapper classes for the sake of backwards compatibility.

As far as creating and instantiating a basic "class" goes, the process will be quite similar to using a constructor function, as in earlier versions of JavaScript. Consider the following examples:

/* JavaScript 1.x "Class" Definition*/
function Foo() {
 this.a = "a";
 this.b = "b";
var myFoo = new Foo(); // class instantiation

/* JavaScript 2.0 Class Definition */
class Bar {
 this.a = "a";
 this.b = "b";
var myBar = new Bar(); // class instantiation

That alone hardy seems worth the overhaul, but classes will provide far more flexibility through its many designators and directives (final, dynamic, extends, implements, etc.). Also note that constructor functions can be changed, whereas classes will be bound as constants, and therefore cannot be changed.

Object Oriented Programming has done to programming what relational databases did to persistence - it has dominated. I can't think of a single thing that I would rather see in JavaScript 2.0 than exactly this.

Compile Time Type Checking

JavaScript 2.0 components can request to be compiled in strict mode. This will test the integrity of several key aspects before execution. A partial list of these checks includes:

  • Static type checking
  • Verification that referenced names are known
  • Checks for illegal assignments to constants
  • Insures that comparisons are only made between valid types

Did I Say Constants?

I sure did. For such an obvious directive, constants have been a long time in coming. Previously JavaScript developers have had to use naming conventions to protect their constants, but that is no longer the case in JavaScript 2.0.

/* JavaScript 1.x constant */
var FOO = 'bar';  // look, I'm all upper cases, so pretty please don't change me

/* JavaScript 2.0 constant */
const FOO = 'bar'; // go ahead, try me...

It may take some time to realize some of the side effects of this change, however, since the constant directive will now be applied to some of the existing core JavaScript objects (such as the pointer to an object's prototype).

Operator Overloading

Cause I am, whatever you say I am, if I wasn't, then why would I... never mind. Misuse it, abuse it, do whatever you want with it. Operators are now whatever you want.

Not Null ("!") Operator

Nullability is a concept that is familiar to anyone who's worked with databases, hibernate annotations in Java, or a whole host of other technologies. In short, it allows you to specify whether an entity can be null or not. Consider the following example:

class Person! {
var x = new Person();

var x = null; // throws error

I'll be honest and admit that I wasn't sure if the error gets thrown on assignment, or when you attempt to read. For now, examples in the documentation are sparse, but either way this will be a handy feature. The mechanism that makes this new operator possible is union types (also new). I won't be delving into those in this article, but they would definitely be worth reading up on at the original source.

Real Namespaces

JavaScript developers have long been implementing namespaces by stuffing everything into a single global object. While this is not a bad convention (and it's much better than cluttering the global namespace), the reality is that it abuses the purpose of objects for the sake of simulating pseudo-namespaces. Well, have a guilty conscience no more, because now you have real bonafide namespaces that are actually made for being, well, namespaces.

Program Units

This is a simple addition, but to me it yields great benefits. Program units allow you to bundle up "program fragments" that don't need to be loaded until requested. This ability has all sorts of potential, not excluding bandwidth optimization.

Perhaps more significant, though, this is also a big step towards providing structured, reusable code libraries. Since the units that you reference will be loaded at most once, you now have a mechanism for maintaining elegant code libraries. Consider the following example:

use unit Person "http://mysite/library/classes/Person";
use unit DisplayUtil "http://mysite/library/utils/DisplayUtil";

var bob = new Person();

Even in this short, fanciful example you can see how your code can start to take on a highly organized and logical structure - much like many of the server side languages you may have worked with. Personally, I think this is one of the strongest improvements found in the specifications.


Well, needless to say, JavaScript 2.0 is shaping up to be a devastatingly awesome improvement. The specifications go on for about 40 pages of size 12 font, so I'm not even going to try and provide a complete overview. But as I've said, everything I've mentioned above can be found in the proposed language overview (PDF) - and there's several more goodies to be found in there as well. Thanks for reading!

Friday, March 14, 2008

Understanding Loose Typing in JavaScript

For many front end developers, JavaScript was their first taste of a scripting and/or interpretive language. To these developers, the concept and implications of loosely typed variables may be second nature. However, the explosive growth in the demand for Web 2.0-ish applications has resulted in a growing number of back end developers that have had to dip their feet into pool of client side technologies. Many of these developers are coming from a background in strongly typed languages, such as C# and Java, and are unfamiliar with both the freedom and the potential pitfalls involved in working with loosely typed variables.

Since the concept of loose typing is so fundamental to scripting in JavaScript, an understanding of it is essential. This article is a top level discussion of loose typing in JavaScript. Since there may be subtle differences in loose typing from language to language, let me constrain this discussion to the context of JavaScript. OK, let's dig in...

What is Loose Typing?

Well, this seems like a good place to start. It is important to understand both what loose typing is, and what loose typing is not. Loose typing means that variables are declared without a type. This is in contrast to strongly typed languages that require typed declarations. Consider the following examples:

/* JavaScript Example (loose typing) */
var a = 13; // Number declaration
var b = "thirteen"; // String declaration

/* Java Example (strong typing) */
int a = 13; // int declaration
String b = "thirteen"; // String declaration

Notice that in the JavaScript example, both a and b are declared as type var. Please note, however, that this does not mean that they do not have a type, or even that they are of type "var". Variables in JavaScript are typed, but that type is determined internally. In the above example, var a will be type Number and var b will be type String. These are two out of the three primitives in JavaScript, the third being Boolean.

JavaScript also has other types beyond primitives. The type diagram for JavaScript is as follows (as per Mozilla):

Ya really - Null and Undefined too.

Note, however, that this distinction between primitives and objects will be dismissed in JavaScript 2.0. You can read more about that here.

Type Coercion

Type coercion is a topic that is closely associated with loose typing. Since data types are managed internally, types are often converted internally as well. Understanding the rules of type coercion is extremely important. Consider the following expressions, and make sure you understand them:

7 + 7 + 7; // = 21
7 + 7 + "7"; // = 147
"7" + 7 + 7; // = 777

In the examples above, arithmetic is carried out as normal (left to right) until a String is encountered. From that point forward, all entities are converted to a String and then concatenated.

Type coercion also occurs when doing comparisons. You can, however, forbid type coercion by using the === operator. Consider these examples:

1 == true; // = true
1 === true; // = false

7 == "7"; // = true
7 === "7"; // = false;

There are methods to explicitly convert a variable's type as well, such as parseInt and parseFloat (both of which convert a String to a Number).

Double negation (!!) can also be used to cast a Number or String to a Boolean. Consider the following example:

true == !"0"; // = false
true == !!"0"; // = true

This obviously is not a definitive reference to loose typing in JavaScript (or type coercion for that matter). I do hope, however, that this will be a useful resource to those who are not familiar with these topics, and a good refresher for those who already are. I have tried to insure that the above is accurate, but if you notice anything incorrect, please let me know! And as always, thanks for reading!

Wednesday, March 12, 2008

I've Moved

Send to: - handle with care

Well, under the recommendation of a few fellow bloggers, I have decided it's time to get my own domain. From now on my blog will be found at

For the time being, Blogger will still be serving my posts from the "blog" sub domain, which will allow me to serve any static content from my root level domain. For me, this beats all the static-page-in-Blogger hacks out there, and I will have a greater degree of control over the site. Thanks to everyone who reads!

Tuesday, March 11, 2008

My Java 7 Wishlist

Well, the JDK7 Project is underway, and despite the fact that I am being moved into the .NET world for some new projects, I wanted to leave some parting thoughts with the Java community. By no means do I consider myself the ultimate authority on the following topics, however, these are a few things that I propose would make Java a better, more friendly, more flexible language.

So here they are, in no particular order, my wish list for Java 7:

1. No More Primitives!

Seriously, primitives had their place and their time, but it's time to let them go. If you're using a boolean instead of Bool to save system resources, then you need to get a server that was made in the last decade. Performance is no longer a valid argument on this one (and that was about the only argument there ever was). OOP is OOP and primitives don't belong in OOP!

2. Tuples

Let me put it this way... how many times have you wanted to do something like this:

return (object1, object2);

See, now you want tuples too. Of course you always have the option of shoving them into some sort of a generic Collection, and then recasting them on the other side. But here's the problem: Collection's are meant to hold a collection of objects, they are NOT intended to be a form of community transit.

Another cool thing about tuples is they let you swap values without using a temporary variable, e.g. (x,y) = (y,x). That one's just for free...

3. Singleton Class Modifier

Do we need it? No. Would it be nice? Absolutely. Just let rules of a singleton Class be handled by the JVM, rather than leaving "singletoness" to be implemented by the designer. I suppose more importantly, singletons would be made thread safe by the JVM, a consideration that is often overlooked by singleton design patterns.

4. Scriptlets Inside JSP 2.0 Custom Tag Bodies

Ya, I know this is JSP, not strictly Java - but I'm stroking with a very broad brush here. I mean, why in the name of all that is good can't we do this?? Yes, scriptlets are inherently evil since the advent of JSTL, but what about those of us cursed with terabytes of legacy code that we do NOT want to convert to JSTL functions? Presumably custom tags still implement doBody() at some point or another, which already supports scriptlets. So again, why???

5. Heredoc String Support

This again is something that we don't need, but that I would definitely like to see. Java developers generally externalize any Strings large enough to justify heredoc format into a properties file - but this has its limitations; take for example a String that needs to contain a variable. I really don't care how it's implemented (e.g., StringBuilder, StringBuffer, plain Jane concatenation), but I want it.

6. Closures

While Java let's you get close to closures (using anonymous inner functions), your code ends up being really ugly and hardly readable. I think closures would be a big step towards making Java a more flexible language (without hurting your eyes at the same time).

7. Rationalize the Collections API

This would be big, it would be rough, and it would make a lot of developers angry. The idea of it actually scares me a little, but I'd contend that it has to happen sooner or later - and the sooner the better. Since my whole argument here is completely stolen, I'll just let you read it at the source.

And that's it. I wanted to make it a top 10 list, but I really didn't have enough to go on. I realize several of these topics are controversial - so let's hear it in the comments.

Friday, March 7, 2008

Total Recall

Reason #84 to make sure you're current with your vehicle's recalls:

Total Recall

Just uncovered this clip on my old computer. This was a tragic/shocking scene that my wife and I passed down in the L.A. area. This reminds me that I heard something about a recall concerning the speed control on our Explorer... better get on that...

Efficient Tag Cloud Algorithm

Hey all - since tag clouds are so popular these days, I thought I'd make a quick post about the algorithm I'm using to generate my tag cloud. I found a few sample algorithms already out there, but many of them seemed either inefficient, or didn't return the size that I was expecting.

Considering that the algorithm I'm using for my blog is running on the client side, I wanted to make sure that it was especially efficient. Here's what I ended up coming up with.

First, let's define the variables that are being used:

The font size is set as a percentage. This is the font-size percentage that the largest (most frequent) tag should be set to.
This is the font-size percentage that the smallest (least frequent) tag should be set to.
This is the number of occurences for the most frequent tag.
This is the number of occurences for the least frequent tag.
This variable should be set inside of the link iterator. It refers to the number of occurences for the current tag.

Before I show some sample code for this, let's look at the actual algorithm for calculating the size:

var size = minPercent + ((max-(max-(count-min)))*(maxPercent-minPercent)/(max-min));

Since count is the only variable that changes during each iteration, we can extract the expression (maxPercent-minPercent)/(max-min) into its own constant and define it outside of the loop. This will save us two subtractions and a division operation for every loop. This now yields the following algorithm:

var multiplier = (maxPercent-minPercent)/(max-min);
var size = minPercent + ((max-(max-(count-min)))*multiplier);

The mathematical brilliance (sorry) behind this simple function isn't immediately obvious by looking at it, but the size returned will adhere to the following rules:

  1. The least occuring tag(s) will have a font-size of minPercent.
  2. The most occuring tag(s) will have a font-size of maxPercent.
  3. Tags with occurence counts in the middle will be scaled linearly.

Ok, let's look at this algorithm in action. The sample below uses a few jQuery methods (you all saw it coming), but this algorithm can certainly survive apart from any JS library. Notice that in the code below, I don't know min or max at the start. This means I have to loop through all of the tags twice, calculating these statistics the first time.

To give this code a real life context, I am generating a tag cloud out of the categories list that blogger generates. The markup that I am looping through is in the following format:

<div class="widget-content" id="categories">
   <a dir="ltr" href="">jQuery</a>
   (<span dir="ltr">6</span>)
   <a dir="ltr" href="">jTruncate</a>
   (<span dir="ltr">2</span>)

And here's the heavily commented javascript:

$().ready(function() {
 var catContainer = $('div#categories');
 // get an array of all the <li>'s
 var categories = catContainer.find('ul li');
 var cloudMarkup = '';
 // set maxPercent/minPercent preferences
 var maxPercent = 150, minPercent = 100;
 // note that max is initialized to a number that I know is lower than the max count
 // and that min is set to a number larger than the known min count
 var max = 1, min = 999, count = 0;
 // loop through each li and calculate statistics
 categories.each(function(i) {
  count = parseInt($(this).find('span').text());
  max = (count > max ? count : max);
  min = (min > count ? count : min);
 var total, link, size;
 var multiplier = (maxPercent-minPercent)/(max-min);
 // loop through each li and generate the markup for the new tag cloud
 categories.each(function(i) {
  count = parseInt($(this).find('span').text());
  link = $(this).find('a');
  size = minPercent + ((max-(max-(count-min)))*multiplier) + '%';
  cloudMarkup += '<a class="cloud_link" style="font-size:' + size + '" href="' + link.attr('href') + '">' + link.text() + '</a> ';
 // replace the html content of the parent container with the new tag cloud

For you jQuery users out there - I am considering turning this into a plugin. I would like to hear from you what the expected markup should look like. For example, <a href="#" rel="[count]">tag</a> or <a href="#">tag ([count])</a>. Hopefully we can come up with something that doesn't completely violate the purpose of the rel tag, like that example! Thanks for your input!

Monday, March 3, 2008

jQuery - It's Here to Stay

So anyone who has been following this blog during its infancy knows that I have dedicated a lot of time to jQuery. Although my official title at work is Software Engineer, I have always had sway towards the client side technologies. Perhaps it's the instant gratification; no compile/build/deploy time, and everyone can appreciate it with no understanding of all the back end magic.

To cut out the story telling, I've found myself doing a lot more JavaScript-ing over the last few releases than my job description would have suggested. Never one to re-invent the wheel, I started researching some of the popular JS libraries out there. This post isn't intended as an analysis of why I eventually settled with jQuery, but suffice it to say that it became the obvious answer to many of our client-side needs.

After discovering the revolutionary ease of DOM selection, traversal, and manipulation in jQuery, I was then blown away by the level of productivity and logicality that chaining permits. If I want a div to fade in, flash 3 times, and then load some external content, I can group these related actions into one logical chain of events... all on the same line.

So apparently I became a believer. But I started wondering lately how popular jQuery has really become? Most of my immediate peers still drool and grovel over Prototype and Mootools (no offense to these other great libraries). My initial understanding was that jQuery must be the underdog struggeling to make a name. Well I did a little research and I was actually surprised by what I found. Check out these results from a Google Trends comparison:

Google Trends: jQuery vs. Scriptaculous vs. Mootools

These results are showing the number of Google queries for 'jquery' vs. 'scriptaculous' vs. 'mootools'. Although the chart doesn't reveal the total number of queries, it would appear that jQuery has received roughly three times the interest of scriptaculous or mootools. Obviously 'prototype' would have been a fairer comparison, but being a common dictionary term, the results would not truly indicate searches for the JS library.

This next chart by Alexa shows the number of page views (as gathered by Alexa) for,, and

Alexa: vs. vs.

This comparison would indicate that mootools is doing better than the Google Trends chart indicated, however jQuery still has a commanding lead. This is great news for jQuery developers. If these numbers are any indication of adoption rates, then we can be sure that development will continue, and be confident in the already supportive community. Well... what more can I say? Congrats to John Resig and the whole jQuery team for delivering a great product, and of course to the whole jQuery community for making it a success!