JavaScript Dollar Sign ($) - What is it for?

Javascript Dollar Sign. A beginner, or even a seasoned JavaScript programmer may be slightly intimidated having once spotted something as ambiguous as the dollar sign ($) in JavaScript code. Seeing for the first time the usage of the Dollar Sign, it may be difficult to grasp having not read any books about JavaScript and jQuery. To explain the usage of the dollar sign in JavaScript code, I need to lay out some general details. In JavaScript, the dollar sign commonly appears in variable definitions and function calls. Let me assure you that there is nothing mysterious about the dollar sign, for it is just a variable (or an identifier) name. There is nothing Greek about it. As an example of this, the insanely popular JavaScript framework, about which I had previously written an article (What is jQuery?) uses the dollar sign to instantiate the main jQuery object.

In many computer programming languages or script languages a variable is also referred to as an identifier. Each programming language has a design whether it be C, C++, PHP, Java or Javascript. Each language design also has a set of rules. For example, in JavaScript the rules for defining variables is that each identifier must start with a letter, the dollar sign ($) or the underscore character (_) and must never start with a digit (such as 0-1) or some of the other characters such as punctuation signs and a few others (because that would confuse the crap out of the compiler). Both of these symbols ($ and _) are special cases and may also appear in the rest of the identifier name. So, as an example, a variable identifier named by five consequent dollar signs such as $$$$$ (or five, or another number of underscores in a row, for that matter) is totally acceptable because it falls within the rules of the JavaScript language syntax. This is simply a language rule that JavaScript programmers must live with. And believe me, there are very good reasons for that.

Once upon a time, there was a global function object, whose identifier's name was a single dollar sign $. This coding practice (lack of the var keyword) was undesirable by the skilled and the aged programmers, because we do not favor global variables in our JavaScript code unless we are cheating. However, the important part is that this function could have been named almost anything such as: a, z or even a single underscore: _

// An example of legal identifier names

var A = function() {
    alert("function A was called");
}

var $ = function() {
    alert("function $ was called");
}

var _ = function() {
    alert("function _ was called");
}

Using other uncommon characters

Furthermore, in addition to the dollar sign and the underscore character, in JavaScript version 1.5 and later, you can also use ISO 8859-1 and Unicode letters such as Ø to name your identifiers. Surprisingly for some, one can also use the \uXXXX Unicode escape sequences where XXXX would be a number such as 0024. What is interesting is that the unicode \u0024 escape sequence translates to, guses what?... the dollar sign. And it is even possible to call the function, literally defined with identifier named \u0024 by refering to it with the dollar sign character! Of course, just because this is possible, it is very uncommon to do this in your code. I consider this an undesirable practice, because not only many programmers are not aware of this, if you use these "techniques" the code starts to look confusing and unreadable.

As you may know, JavaScript is an object-oriented programming language by design. There are several different ways to assign a value to an identifier. For example, when we use the keyword var, the JavaScript will create a variable in the current (or local) scope of the code block you are adding the code to. If we skip the var keyword, the variable will still be created, but in the global scope of your program, which means it would be visible from anywhere in the (.js) file. Again, try to avoid using globals. I know this is a page about the dollar sign, but if it is not yet obvious to you, the no-globals rule will surface once you work with large-scale projects, multiple components written by someone else and/or in a team of a few other software engineers. So if someone tells you it is okay to use globals, and create variables without the var keyword - don't believe their lies.

One more thing. Because JavaScript variables are objects by design you can assign functions to your variables. You can even assign "member" functions to functions that already exist. But by trying to assign a function to a function object that does not yet exist will not compile in JavaScript. If you really want to get in depth with this, I will ask you to pay careful attention to the code shown below.

Now, with the knowledge you've gained from this article, and without copy and pasting the code to test it in your browser, can you tell whether the following code will compile?

<script type = "text/javascript">
window.onload = function()
{
    // Define function objects
    var func1   = function() { alert("hello from func1"); }
    func1.func2 = function() { alert("hello from func1.func2"); };
    var _       = function() { alert("hello from _"); }
    var \\u0024  = function() { alert("hello from $ defined as \u0024"); }
    var Ø       = function() { alert("hello from Ø"); }
    var $$$$$   = function() { alert("hello from $$$$$"); }
    var $func$  = function() { alert("hello from $func$"); }
    var __      = function() { alert("hello from __"); }
    _.$         = function() { alert("hello from _.$"); }
    __.__       = function() { alert("hello from __.__"); }
    $.member    = function() { alert("hello from $.member"); }

    // Call functions defined above one by one
    func1();
    func1.func2();
    _();
    $();
    Ø();
    $$$$$();
    $func$();
    $.member();
    _.$();
    __();
    __.__();
}
</script>

Permitted identifier characters

By convention, the dollar sign ($), the underscore (_) and even some ASCII character are permitted to be used anywhere in a JavaScript identifier (Source: Ecma Script documentation (7.6 Identifiers, ECMA-262, 3rd Ed.) the dollar sign is intended for use only in mechanically generated code. This means that we do not want to use the dollar sign ($) in our indentifier names, unless we are writing a framework. The following is a list of permitted characters that can be used anywhere in an identifier name:

    IdentifierName ::
    IdentifierStart
    IdentifierName IdentifierPart
    IdentifierStart ::
    UnicodeLetter
    $
    _
    UnicodeEscapeSequence
    IdentifierPart ::
    IdentifierStart
    UnicodeCombiningMark
    UnicodeDigit
    UnicodeConnectorPunctuation
    UnicodeEscapeSequence

The point of this article is to show you that the dollar sign character (implemented by the popular js framework called Prototype and then picked up by the jQuery developers) is simply an identifier name, nothing more. Why is it used by programmers? Well, it is a very convenient way to name a function that has a distinct purpose in framework code. And this is the reason jQuery's main object, defined as the dollar sign, can be used interchangeably with the actual object whose name is jQuery. We do not use $ in our custom code, we use the jQuery object. If you are familiar with jQuery and you have paid close attention to its documentation, using the $ alias for the actual object named jQuery in your jQuery plugin code is not desired, although, for some reason it is very common among programmers who find it cute.
Dollar Sign ($) Usage Summary

The dollar sign usage is semantics. It is an identifier name. Psychologically, it looks cute and convenient. Internally, it is just a function or an alpha-numeric variable reference. But it really makes no difference whether you use $ or _ or any other character as explained in the article on my website linked to from this page by the author of this page, for which I thank him.

The usage of the $, as pointed out by the Ecmascript specification, is a character that is allowed to be contained in a variable identifier name. Using the $ as the only character in an identifier name sure does make it look strange, but the difference is semantic in nature. As far as I know, doing so is no different than using any other character such as a, or b in an identifier name.

Again, Ecmascript specification documentation tells us that the $ should be used by internal code such as the jQuery framework simply out of convenience. So this means we should not use it in our code just because it looks cool, unless we are programming a framework that can really benefit from it, because it makes the global framework object unique and separate from the rest of the code.

jQuery Book Reference List:

1. Learning jQuery: Better Interaction Design and Web Development with Simple JavaScript Techniques

2. jQuery Reference Guide: A Comprehensive Exploration of the Popular JavaScript Library

3. jQuery in Action
Did this article help you learn something new?

If the content on this website somehow helped you to learn something new, please let others know about it by sharing it on your website or on your Facebook page with your friends. In addition you can help by making a donation or bookmarking this site.

0 comments:

Post a Comment