Sign of the Dollar
September 13, 2007 9:02 pmI was perusing some JavaScript the other day and saw a strange notation that I had never seen before:
$("report")
"What is this?", I thought. It looks like Perl or PHP -- have I missed some big piece of JavaScript or is this some new feature? In a word: No.
It turns out that this is actually a function contained in the Prototype JavaScript Framework. The definition of the function is along the lines of:
-
function $() {
-
var elements = new Array();
-
for (var i = 0; i <arguments.length; i++) {
-
var element = arguments[i];
-
if (typeof element == 'string')
-
element = document.getElementById(element);
-
if (arguments.length == 1)
-
return element;
-
elements.push(element);
-
}
-
return elements;
-
}
Functionally, this is nothing special: pass in a name and get back the object. Or pass in an array and get back an array of objects. The really cool thing is the simple elegance of this method and how it cleans up your code.
-
// 'Classic' way
-
document.getElementById('userName').value = 'admin';
-
-
// Dollar way
-
$('userName').value = 'admin';
This is so simple, that it seems obvious! This saves on programmer typing, saves on page size and makes the code more readable.
In a word: beautiful.
Categories: IT, Tech
2 Comments »


2 Responses to “Sign of the Dollar”
While it is concise, the problem with the $ notation is that it violates the principle of keeping things obvious. After all, *you* had to go digging around to find out what exactly was going on. So it’s a clever idea. But, clever code should be readable code, too, in order to be worth keeping.
The longer way is at least obvious to a casual observer, even somebody not familiar with Javascript. The longer way is also idiomatic, i.e. not surprising people who are familiar with Javascript.
*That’s* beautiful. I do grant, however, that if I ever need to obfuscate and/or compress my Javascript code, that trick could come in handy. So, thanks for pointing it out.
(By the way, how are you preserving the syntax coloring in your blog posts?)
Syntax coloring is achieved using the iG:Syntax Hiliter which is a wordpress plugin that uses the GeSHi syntax highlighting library.
Care to comment?