The Javascript Dollar Sign ($) Function

Recently, I’ve been seeing a lot of Javascript functions prefixed with a dollar sign ($) or simply named $. I thought, what sort of magical property does the dollar sign have in Javascript? What sort of esotericism had I uncovered?

The Dollar Sign Magician

I checked the O’Reilly Rhinoceros book, and found that the dollar sign has no special properties.

However, I have come to discover that dollar sign function has become the more-or-less de facto shortcut to document.getElementById(). Let’s face it, we all use document.getElementById() a lot. Not only does it take time to type, but it adds bytes to your code as well.

Here’s the version from prototype.js, which can return more than just a single element:

function $(element) {
  if (arguments.length > 1) {
    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
      elements.push($(arguments[i]));
    return elements;
  }
  if (Object.isString(element))
    element = document.getElementById(element);
  return Element.extend(element);
}

Because it has become a common shortcut to document.getElementById(), it means that various Javascript libraries should play nicely together: if the dollar sign function in one .js file is overwritten by the same dollar sign function in another .js file, everything should still work. That also means that creating your own dollar sign function that does something different is probably not a good idea.

In case you were wondering, the underscore has no special properties either. But let’s face it, $(‘myVal’) looks more like programming than _(‘myVal’).

Update 2012
By now, the most common use of the $() function is as synonym for jQuery() in the popular jQuery Javascript framework. It returns a jQuery object (or objects), which includes much more than just a reference to the DOM element. (In jQuery, you can still access the underlying DOM element using .get().)

Likewise, the Prototype code I cited above also returns more than just a reference to a DOM element, as it returns an extended version of the element. As such, Prototype and jQuery will almost certainly not work well together in the majority of cases.

Tags: , , ,

Monday, April 7th, 2008 Javascript

19 Comments to The Javascript Dollar Sign ($) Function

  1. Wow, that is a great little chunket of data, and a great idea. I never encountered this before, but I am totally going to start using it.

    Oh, I also find it interesting that wordpress doesn’t hate you when you paste code into it. What’s your secret?

  2. Harry on April 7th, 2008
  3. You know, I copied that code directly off of the prototype.js site, and it retained the formatting when I pasted it into the editor. I checked the code, and it’s just wrapped in a <pre></pre> tag. I think a <code></code> tag should work, too.

  4. chris on April 8th, 2008
  5. hrm.
    I wonder why it’s hating on me. perhaps its because I have some tags, including pre tags in my code, though I thought I went through before hand and changed all the < to html entities, so that shouldn’t have fired.

  6. Harry on April 8th, 2008
  7. Any thoughts on the empty WP function in the WP class in WordPress?

    function WP() {
    // Empty.
    }

    http://wordpress.taragana.net/nav.html?index.html

  8. jonny on May 29th, 2008
  9. I found your posting from Google. Using the $ as a function name is a violation of the Javascript/ECMAScript specification, and should never be done. (Unless you’re the interpreter, you’re not allowed to use $.)

    The spec is a PDF file, but look at section 7.6 on page 26.

    And yes, the majority of web frameworks (usually developed by people who are rabid about following HTML/XHTML/CSS specifications) almost all violate the ECMAScript specification– I love hypocrisy.

  10. James Schend on June 9th, 2008
  11. @James:

    That’s good to know. I looked up the info you mentioned, in case others are curious:

    “The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.” (ECMAScript Language Specification: http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf)

    I can settle for an underscore!

  12. Chris Herdt on June 9th, 2008
  13. I found this code on rjobrien.com in the “print friendly” button at the bottom of the page.
    Can someone explain to me what is going on here?

    onclick=”$(‘.print_toggle’).toggle(‘fast’);”

  14. Phil Jones on July 10th, 2008
  15. @Phil:

    It looks like that’s some jQuery code. $(‘.print_toggle’) should return all elements with the class print_toggle, and .toggle(‘fast’) indicates that the specified element(s) should show/hide (depending on their current state) fast (describes the animation).

    The ‘fast’ argument should be superfluous, as according to the jQuery docs, toggle() doesn’t take any arguments–but I notice that the transition is animated on http://www.rjobrien.com/. Maybe someone with more experience in jQuery can answer that.

    http://docs.jquery.com/Selectors/class
    http://docs.jquery.com/Effects/toggle

    It’s a pretty slick effect for very little code.

  16. Chris Herdt on July 11th, 2008
  17. I would like to point out that the JS 1.1 spec (’96) states that the ‘$’ and ‘_’ can be used in identifiers and are valid.
    url: planetpdf.com/codecuts/pdfs/tutorial/jsspec.pdf
    essentially making the use of $() {} a valid function identifier. Last I recalled the ECMA Script language was developed after (and based on) Javascript by Netscape and JScript from Microsoft.

  18. seo web design company on June 23rd, 2009
  19. isn’t the “_” meant to indicate that you shouldn’t tamper with this thing since it’s used internally?. Kind of private? ^^

  20. walkman69 on June 22nd, 2010
  21. Nice. Handy shortcut but hard to decipher without prior knowledge of it. Thanks for posting!

  22. Brad on October 25th, 2010
  23. Excellent. Saved me from lots of confusion and searching.
    JS libraries such as JQuery take this shorthand definition for granted. So without knowing this, their tutorials and example codes become difficult to understand for the newcomer.
    And thanks for putting “Dollar Sign” in the post title, because searching for “Javascript $” doesn’t give any useful results ;)

  24. Scrontch on November 17th, 2010
  25. Thanks for the clarification. But what does the dollar sign mean in this code?

    // From TryHaskell
    // https://github.com/chrisdone/tryhaskell

    function ($) {

    }

  26. Andrew Pennebaker on March 19th, 2011
  27. I can’t say what exactly it means in that context without diving into the project code, but in general it is just a variable reference. In this case it is the variable reference for the argument passed to an anonymous function.

  28. Chris Herdt on March 21st, 2011
  29. Thanks Chris, I just started looking at JQuery and then had to find your post. Scrontch is right – they just slapped it in there and expected me to know what they meant by it.

  30. Bill on August 19th, 2011
  31. Spelling out meaningful function names is always better than trying to prevent bytes added to your code.

  32. Dominik Kaspar on October 20th, 2011
  33. Dominik: I agree, although at this point in time the $() is well-established. There’s a substantial codebase out there that uses it, so I don’t think it’s going anywhere soon.

    Regarding jQuery, $() can also be written as jQuery(), so built-in is the option to use a more explicit function name (see jQuery API).

    Prototype, on the other hand, does not seem to offer the same: Prototype API. You could create your own alias (e.g. getElements = $), but that creates its own hassles.

  34. Chris Herdt on October 20th, 2011
  35. The dollar function is a function that takes in some sort of identifier for an HTML element or elements and returns a jQuery object. It’s the main function used by jQuery that’s the basis for the whole framework.

    By no means is it a “shortcut” for document.getElementById(). Nice theory, though. Google next time!

  36. Sean on June 18th, 2012
  37. Sean, you are correct that the jQuery() function (which can also be written as $()) returns a lot more than just a reference to a DOM object.

    Although the post was originally written in 2008 about Prototype’s $() function (which also returned more than just a reference to a DOM object), people who are running into the $() function today in 2012 are likely seeing it in a jQuery context. I’ll amend the post accordingly.

  38. Chris Herdt on August 12th, 2012