1074

I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?

(I'm not asking about $('p.foo') syntax that you see in jQuery and others, but normal variables like $name and $order)

Yi Jiang
  • 46,385
  • 16
  • 133
  • 131
Ken
  • 71,088
  • 29
  • 81
  • 100
  • 18
    It's probably a habit picked up from Perl programming. (edit: or PHP) – brien Oct 15 '08 at 18:27
  • 5
    Some languages require it, such as PHP or Perl - I'm guessing that the dev didn't remember that it's not needed in javascript. – Rich Bradshaw Oct 15 '08 at 18:30
  • 3
    or they didn't want to be bothered to drop the habit. This is most likely the correct answer, since so many developers who hack together their own webpage do so using PHP and javascript. – BlueRaja - Danny Pflughoeft Jul 20 '11 at 22:08
  • @DonaldDuck I think you might have your duplicates the wrong way round - this is 7 months older than your link – Ken Nov 19 '17 at 11:08
  • 1
    @Ken According to [this answer](https://meta.stackexchange.com/a/147651/349538), it's not the age that matters but how good the answers are. I personally think the answers to the other question are better, which is why I voted to close this one as a duplicate. If you think the answers to this one are better, you can vote to close the other one as a duplicate. – Donald Duck Nov 19 '17 at 14:06
  • As one of those guys 'hacking' together web pages, I use $variable in javascript because I learned php long before I learned javascript. And it's not about dropping the habbit, for me it's about having my JS code be readable at a glance. If I'm looking at code that doesn't use dollar signs, it's a lot slower for my brain to process. So the short version of that is, it makes my code nice and readable and consistent among the two languages I use all the time. – l008com Apr 14 '18 at 12:20

16 Answers16

1461

Very common use in jQuery is to distinguish jQuery objects stored in variables from other variables.

For example, I would define:

var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself

I find this to be very helpful in writing jQuery code and makes it easy to see jQuery objects which have a different set of properties.

Arsen Khachaturyan
  • 6,472
  • 4
  • 32
  • 36
jonstjohn
  • 56,752
  • 8
  • 41
  • 55
  • 104
    This is the REAL Hungarian notation. It conveys info about what is stored in the variable beyond what the variable name does. A++ would Hungary again. – Artemis Nov 29 '13 at 01:54
  • 3
    I wish the jquery documentation used this notation as well... It is indeed really helpful. – pedromanoel Jan 28 '14 at 11:05
  • 1
    @Artemis I picked up Hungarian almost 20 years ago and have never been able to stop using it. Over the years a lot of people have expressed great displeasure with my use of it but it's so helpful I can't understand why. – Night Owl Feb 18 '14 at 03:59
  • 1
    @Artemis To quote from another page "However, this usage might be arguably [Apps Hungarian](https://en.wikipedia.org/wiki/Hungarian_notation#Systems_vs._Apps_Hungarian) as the variable "represent a jQuery object" and not System Hungarian (which is normally considered "the bad kind" or indicative of HOW the variable will be stored by the system)." – LocalPCGuy May 31 '14 at 01:12
  • 11
    Thumbs up for the $. But underscores in variable names should be prevented, normal JS-Variables should use camelCase. email_fields -> emailField. Only valid use-case for _ is as a prefix for private/protected properties. – cschuff Sep 22 '14 at 12:18
  • 12
    @cschuff That's quite the statement... I prefer underscores for all local variables, and reserve camel-case for properties of prototype objects. – Paul Feb 20 '15 at 17:27
  • 1
    @cschuff JS isn't a language created with typed constraints on how you choose to write your methods or variable names, that should not even be a suggestion as that's more of an individual and/or team based decision... That aside *I* prefer underscore or snake case because I code for readability as well and is easier to read 'rotation_current_form_name' than 'rotationCurrentFormName', there's a study done about that too. – Carlos Feb 14 '20 at 18:15
  • Underscores as separators make it much easier for me to read my own code. What is the reason behind the concern about them ? If it's a good reason, I would stop doing it. On the other hand, I HATE leading underscores that I often see done for local or private class attributes and what not. So, what to do? Camel case seems to be giving way to all lower case. I just can't get a handle on the conventions. – user3314553 Mar 27 '20 at 19:36
259

In the 1st, 2nd, and 3rd Edition of ECMAScript, using $-prefixed variable names was explicitly discouraged by the spec except in the context of autogenerated code:

The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.

However, in the next version (the 5th Edition, which is current), this restriction was dropped, and the above passage replaced with

The dollar sign ($) and the underscore (_) are permitted anywhere in an IdentifierName.

As such, the $ sign may now be used freely in variable names. Certain frameworks and libraries have their own conventions on the meaning of the symbol, noted in other answers here.

Mark Amery
  • 110,735
  • 57
  • 354
  • 402
cic
  • 6,858
  • 3
  • 21
  • 34
  • 3
    While this may be true, does it really help answer the OP's question? The currently-accepted answer is better - when an novice JS programmer sees `$variable`, it's likely because it contains an entire jQuery object. – rinogo Mar 24 '16 at 19:36
  • 16
    @rinogo It answers the question with some absolute truth which doesn't depend on assumptions about the used libraries. – Oriol Apr 09 '16 at 19:36
  • What does mechanically generated code mean in this context? – yoyo_fun Apr 28 '16 at 13:39
  • 1
    @yoyo_fun: Code that is generated by a computer rather than written by a human. – cic Apr 28 '16 at 14:11
  • @cic what would be some applications of this scenario? Why would a computer generate javascript code? – yoyo_fun Apr 28 '16 at 14:13
  • 1
    @yoyo_fun: https://github.com/jashkenas/coffeescript/wiki/list-of-languages-that-compile-to-js – cic Apr 28 '16 at 14:18
  • 3
    "It answers the question with some absolute truth". Actually, the truth was that devs were completely ignoring this remark from the language spec... and probably still are. :) – Stijn de Witt Aug 01 '16 at 22:05
61

As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).

In short you can use the $ whenever you want. (The interpreter won't complain.) The question is when do you want to use it?

I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.

For example:

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

That seems like a reasonable convention.

Wesley Murch
  • 95,417
  • 36
  • 177
  • 220
Benry
  • 5,208
  • 1
  • 22
  • 25
  • JQuery does NOT use this in identifiers, the reason for $.X being there is simply having to type less - jQuery.X is identical, in fact $.X is a namespace-alias for jQuery.X - every jQuery functionality is within the jQuery-ns, not $ – specializt Jul 12 '13 at 04:15
  • 5
    @specializt as I said 5 years ago "or as an entire identifier". By identifier I mean the standard CS definition which is a lexical token that is not a keyword in the language. In this case $ and jQuery are two different identifiers that reference the same value. But they are both identifiers nonetheless. – Benry Jul 12 '13 at 05:32
56

In the context of AngularJS, the $ prefix is used only for identifiers in the framework's code. Users of the framework are instructed not to use it in their own identifiers:

Angular Namespaces $ and $$

To prevent accidental name collisions with your code, Angular prefixes names of public objects with $ and names of private objects with $$. Please do not use the $ or $$ prefix in your code.

Source: https://docs.angularjs.org/api

Travis Watson
  • 1,657
  • 1
  • 16
  • 25
43

I was the person who originated this convention back in 2006 and promoted it on the early jQuery mailing list, so let me share some of the history and motivation around it.

The accepted answer gives this example:

var $email = $("#email"); // refers to the jQuery object representation of the dom object
var email_field = $("#email").get(0); // refers to the dom object itself

But that doesn't really illustrate it well. Even without the $, we would still have two different variable names here, email and email_field. That's plenty good right there. Why would we need to throw a $ into one of the names when we already have two different names?

Actually, I wouldn't have used email_field here for two reasons: names_with_underscores are not idiomatic JavaScript, and field doesn't really make sense for a DOM element. But I did follow the same idea.

I tried a few different things, among them something very similar to the example:

var email = $("#email"), emailElement = $("#email")[0];
// Now email is a jQuery object and emailElement is the first/only DOM element in it

(Of course a jQuery object can have more than one DOM element, but the code I was working on had a lot of id selectors, so in those cases there was a 1:1 correspondence.)

I had another case where a function received a DOM element as a parameter and also needed a jQuery object for it:

// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
    var emailJQ = $(email);
    // Now email is the DOM element and emailJQ is a jQuery object for it
}

Well that's a little confusing! In one of my bits of code, email is the jQuery object and emailElement is the DOM element, but in the other, email is the DOM element and emailJQ is the jQuery object.

There was no consistency and I kept mixing them up. Plus it was a bit of a nuisance to keep having to make up two different names for the same thing: one for the jQuery object and another for the matching DOM element. Besides email, emailElement, and emailJQ, I kept trying other variations too.

Then I noticed a common pattern:

var email = $("#email");
var emailJQ = $(email);

Since JavaScript treats $ as simply another letter for names, and since I always got a jQuery object back from a $(whatever) call, the pattern finally dawned on me. I could take a $(...) call and just remove some characters, and it would come up with a pretty nice name:

$("#email")
$(email)

Strikeout isn't perfect, but you may get the idea: with some characters deleted, both of those lines end up looking like:

$email

That's when I realized I didn't need to make up a convention like emailElement or emailJQ. There was already a nice convention staring at me: take some characters out of a $(whatever) call and it turns into $whatever.

var $email = $("#email"), email = $email[0];
// $email is the jQuery object and email is the DOM object

and:

// email is a DOM element passed into this function
function doSomethingWithEmail( email ) {
    var $email = $(email);
    // $email is the jQuery object and email is the DOM object
    // Same names as in the code above. Yay!
}

So I didn't have to make up two different names all the time but could just use the same name with or without a $ prefix. And the $ prefix was a nice reminder that I was dealing with a jQuery object:

$('#email').click( ... );

or:

var $email = $('#email');
// Maybe do some other stuff with $email here
$email.click( ... );
Michael Geary
  • 26,814
  • 8
  • 56
  • 71
21

Stevo is right, the meaning and usage of the dollar script sign (in Javascript and the jQuery platform, but not in PHP) is completely semantic. $ is a character that can be used as part of an identifier name. In addition, the dollar sign is perhaps not the most "weird" thing you can encounter in Javascript. Here are some examples of valid identifier names:

var _       = function() { alert("hello from _"); }
var \u0024  = function() { alert("hello from $ defined as u0024"); }
var Ø       = function() { alert("hello from Ø"); }
var $$$$$   = function() { alert("hello from $$$$$"); }

All of the examples above will work.

Try them.

Matt
  • 70,063
  • 26
  • 142
  • 172
8

The $ character has no special meaning to the JavaScript engine. It's just another valid character in a variable name like a-z, A-Z, _, 0-9, etc...

  • 2
    true but not what was asked. I came here wanting to understand why it was used and it seems that the case where I was seeing it was to discern a var containing a jquery object between a var containing a dom object. – rtpHarry Jun 01 '11 at 22:42
  • 3
    @rtpHarry you were not the one asking the question, and the question "why" has been answered here adequately. This has nothing to do with JQuery, as also was stated in the question. In fact, I think the answer above fits the question best - sometimes if you want to grasp something you need the smallest clearest answer - `$` carries no special meaning in JavaScript. Period. – amn Nov 28 '13 at 11:05
  • I find that certain .. ahem ... people want to add dollar signs to variable names to make things seem more angular-ish. – 111 Mar 19 '15 at 16:36
2

Since _ at the beginning of a variable name is often used to indicate a private variable (or at least one intended to remain private), I find $ convenient for adding in front of my own brief aliases to generic code libraries.

For example, when using jQuery, I prefer to use the variable $J (instead of just $) and use $P when using php.js, etc.

The prefix makes it visually distinct from other variables such as my own static variables, cluing me into the fact that the code is part of some library or other, and is less likely to conflict or confuse others once they know the convention.

It also doesn't clutter the code (or require extra typing) as does a fully specified name repeated for each library call.

I like to think of it as being similar to what modifier keys do for expanding the possibilities of single keys.

But this is just my own convention.

Brett Zamir
  • 12,481
  • 5
  • 45
  • 68
2

${varname} is just a naming convention jQuery developers use to distinguish variables that are holding jQuery elements.

Plain {varname} is used to store general stuffs like texts and strings. ${varname} holds elements returned from jQuery.

You can use plain {varname} to store jQuery elements as well, but as I said in the beginning this distinguishes it from the plain variables and makes it much easier to understand (imagine confusing it for a plain variable and searching all over to understand what it holds).

For example :

var $blah = $(this).parents('.blahblah');

Here, blah is storing a returned jQuery element.

So, when someone else see the $blah in the code, they'll understand it's not just a string or a number, it's a jQuery element.

ketan
  • 17,717
  • 41
  • 50
  • 83
2

As I have experienced for the last 4 years, it will allow some one to easily identify whether the variable pointing a value/object or a jQuery wrapped DOM element

Ex:
var name = 'jQuery';
var lib = {name:'jQuery',version:1.6};

var $dataDiv = $('#myDataDiv');

in the above example when I see the variable "$dataDiv" i can easily say that this variable pointing to a jQuery wrapped DOM element (in this case it is div). and also I can call all the jQuery methods with out wrapping the object again like $dataDiv.append(), $dataDiv.html(), $dataDiv.find() instead of $($dataDiv).append().

Hope it may helped. so finally want to say that it will be a good practice to follow this but not mandatory.

Naga Srinu Kapusetti
  • 1,259
  • 14
  • 12
0

While you can simply use it to prefix your identifiers, it's supposed to be used for generated code, such as replacement tokens in a template, for example.

Ryan Abbott
  • 5,117
  • 7
  • 29
  • 33
-1

Angular uses is for properties generated by the framework. Guess, they are going by the (now defunct) hint provided by the ECMA-262 3.0.

-3

$ is used to DISTINGUISH between common variables and jquery variables in case of normal variables. let you place a order in FLIPKART then if the order is a variable showing you the string output then it is named simple as "order" but if we click on place order then an object is returned that object will be denoted by $ as "$order" so that the programmer may able to snip out the javascript variables and jquery variables in the entire code.

Saurabh Saluja
  • 391
  • 3
  • 6
-4

If you see the dollar sign ($) or double dollar sign ($$), and are curious as to what this means in the Prototype framework, here is your answer:

$$('div');
// -> all DIVs in the document.  Same as document.getElementsByTagName('div')!

$$('#contents');
// -> same as $('contents'), only it returns an array anyway (even though IDs must be unique within a document).

$$('li.faux');
// -> all LI elements with class 'faux'

Source:
http://www.prototypejs.org/api/utility/dollar-dollar

RussellW
  • 225
  • 4
  • 7
-5

The reason I sometimes use php name-conventions with javascript variables: When doing input validation, I want to run the exact same algorithms both client-side, and server-side. I really want the two side of code to look as similar as possible, to simplify maintenance. Using dollar signs in variable names makes this easier.

(Also, some judicious helper functions help make the code look similar, e.g. wrapping input-value-lookups, non-OO versions of strlen,substr, etc. It still requires some manual tweaking though.)

not-just-yeti
  • 16,609
  • 1
  • 16
  • 15
-7

A valid JavaScript identifier shuold must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Details:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variables

Pang
  • 8,605
  • 144
  • 77
  • 113
  • 3
    The questions wasn't 'Can a JavasScript variable start with a $?', but 'Why would a ...' . thee OP was looking for a reason to use such a naming convention. – Steve Ives Sep 11 '19 at 09:30