1145

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
50.2k16 gold badges139 silver badges137 bronze badges
asked Oct 15, 2008 at 18:26
7
  • 23
    It's probably a habit picked up from Perl programming. (edit: or PHP) Commented Oct 15, 2008 at 18:27
  • 8
    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. Commented Oct 15, 2008 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. Commented Jul 20, 2011 at 22:08
  • 3
    @DonaldDuck I think you might have your duplicates the wrong way round - this is 7 months older than your link Commented Nov 19, 2017 at 11:08
  • 2
    @Ken According to this answer, 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. Commented Nov 19, 2017 at 14:06

16 Answers 16

1541

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
8,4304 gold badges46 silver badges47 bronze badges
answered Feb 16, 2009 at 15:42
Sign up to request clarification or add additional context in comments.

8 Comments

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.
I wish the jquery documentation used this notation as well... It is indeed really helpful.
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 That's quite the statement... I prefer underscores for all local variables, and reserve camel-case for properties of prototype objects.
@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.
|
278

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
158k94 gold badges435 silver badges477 bronze badges
answered Oct 15, 2008 at 18:59

7 Comments

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 It answers the question with some absolute truth which doesn't depend on assumptions about the used libraries.
@yoyo_fun: Code that is generated by a computer rather than written by a human.
"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. :)
|
70

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( ... );
answered Feb 1, 2018 at 9:05

1 Comment

I started with a programming language that was strictly typed, and so whenever I want to signify a jQuery variable, I'll use something like oEmail = $('#email'). The "o" prefix reminds me that it's an object, as opposed to a string or number.
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.

No Results Found
103k38 gold badges199 silver badges232 bronze badges
answered Oct 15, 2008 at 22:57

2 Comments

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 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.
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

answered Aug 30, 2012 at 22:51

Comments

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
75.5k26 gold badges156 silver badges181 bronze badges
answered Aug 8, 2009 at 0:34

Comments

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...

answered Jul 28, 2009 at 15:26

3 Comments

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 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.
I find that certain .. ahem ... people want to add dollar signs to variable names to make things seem more angular-ish.
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.

answered May 4, 2014 at 14:52

Comments

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
19.4k42 gold badges68 silver badges107 bronze badges
answered Jan 21, 2015 at 9:38

2 Comments

You've just rephrased the accepted answer from 6 years ago.
I suppose that does not make the answer "low-quality".
1

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.

InSync
12.2k5 gold badges22 silver badges60 bronze badges
answered Sep 5, 2015 at 19:27

Comments

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.

answered Oct 15, 2008 at 18:33

1 Comment

True six years ago, but no longer.
-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.

answered Apr 18, 2012 at 14:07

Comments

-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.

answered May 4, 2013 at 9:59

Comments

-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

answered Jul 20, 2011 at 22:03

1 Comment

The OP specifically states that he is not asking about this form of the dollar prefix.
-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.)

answered Feb 21, 2011 at 12:49

Comments

-6

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
10.2k146 gold badges87 silver badges126 bronze badges
answered Oct 21, 2015 at 10:14

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.