2
votes

I don't grok the idea/purpose/use of Javascript $, as in

function $(id) { return document.getElementById(id); }

Could someone please explain or point me at an explanation?

Thanks!

-- Pete

5
had to google grok. That's a new one to me. - Doug Chamberlain
$ is just a variable name. It can be confusing at first blush since many other languages use '$' to denote a variable... but in the JS case it can be the whole name. Plus function names are also variables which means you can have var $='hello'; or function $() {} or even var $=function() {}; (2nd and 3rd result in the same) helpful primer - Rudu

5 Answers

8
votes

When you see JavaScript code that involves lots of $(foo) function calls, it's probably using either the jQuery or the Prototype web development frameworks. It's just an identifier; unlike a lot of other languages, identifiers (function and variable names) can include and start with "$".

7
votes

In your code it is the name of a function.

function $(id) { return document.getElementById(id); }
$("my_id")

function myfunc(id) { return document.getElementById(id); }
myfunc("my_id")

Two functions, two different identifiers.

2
votes

Most commonly this is used by JQuery - specifically, JQuery creates an object with a reference of $ which has various methods to simplify page manipulation.

It's technically possible for anything to attach a class to $

2
votes

It's just the name of a function called $(). The dollar sign ($) is a valid character for identifiers in JavaScript. jQuery, for example, uses it as a shorthand alias for the jQuery() function.

2
votes

There are two main reasons to use $ as a function name, especially in frameworks like jQuery:

  • It's short but distinctive - you're going to use it all over the place, so you don't want it to take up too much space.
  • When used as a DOM element selector, the function and its parameters together kind of look like a Perl/PHP/Java properties variable - and it kind of works like that as well, since the main purpose is to do something with the selected DOM elements.