Why would a JavaScript variable start with a dollar sign? [duplicate]
Asked Answered
B

16

1133

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)

Bellini answered 15/10, 2008 at 18:26 Comment(7)
It's probably a habit picked up from Perl programming. (edit: or PHP)Tameratamerlane
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.Hamlet
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.Reverent
@DonaldDuck I think you might have your duplicates the wrong way round - this is 7 months older than your linkBellini
@Bellini 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.Jasper
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.Vania
The $ sign is to indicate you that you are wasting your time and also giving it to capitalist people that contractes you to do their dirty capitalist jobs. It's in fact, a private joke created from the powerfup people that rule the world that you are living in. That'$ All.Sixteenmo
G
1528

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.

Generalissimo answered 16/2, 2009 at 15:42 Comment(8)
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.Memorabilia
I wish the jquery documentation used this notation as well... It is indeed really helpful.Milkmaid
@Memorabilia 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.Apocarpous
@Memorabilia To quote from another page "However, this usage might be arguably 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)."Serbocroatian
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.Deciliter
@Deciliter That's quite the statement... I prefer underscores for all local variables, and reserve camel-case for properties of prototype objects.Reef
@Deciliter 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.Spikes
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.Greenish
T
274

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.

Tagmemics answered 15/10, 2008 at 18:59 Comment(7)
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.Commeasure
@Commeasure It answers the question with some absolute truth which doesn't depend on assumptions about the used libraries.Jiva
What does mechanically generated code mean in this context?Rosenzweig
@yoyo_fun: Code that is generated by a computer rather than written by a human.Tagmemics
@cic what would be some applications of this scenario? Why would a computer generate javascript code?Rosenzweig
@yoyo_fun: github.com/jashkenas/coffeescript/wiki/…Tagmemics
"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. :)Cohbath
S
63

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( ... );
Syllabify answered 1/2, 2018 at 9:5 Comment(1)
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.Hircine
P
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.

Percy answered 15/10, 2008 at 22:57 Comment(2)
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 $Sciatica
@Sciatica 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.Percy
T
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

Talkington answered 30/8, 2012 at 22:51 Comment(0)
R
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.

Reeta answered 8/8, 2009 at 0:34 Comment(0)
T
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...

Tardiff answered 28/7, 2009 at 15:26 Comment(3)
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.Stegall
@Stegall 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.Huan
I find that certain .. ahem ... people want to add dollar signs to variable names to make things seem more angular-ish.Guenther
C
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.

Control answered 4/5, 2014 at 14:52 Comment(0)
C
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.

Collative answered 21/1, 2015 at 9:38 Comment(2)
You've just rephrased the accepted answer from 6 years ago.Bellini
I suppose that does not make the answer "low-quality".Holston
I
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.

Interventionist answered 5/9, 2015 at 19:27 Comment(0)
D
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.

Delafuente answered 15/10, 2008 at 18:33 Comment(1)
True six years ago, but no longer.Phebe
D
-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.

Deciare answered 18/4, 2012 at 14:7 Comment(0)
I
-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.

Ideational answered 4/5, 2013 at 9:59 Comment(0)
O
-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

Orientation answered 20/7, 2011 at 22:3 Comment(1)
The OP specifically states that he is not asking about this form of the dollar prefix.Halverson
G
-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.)

Garmon answered 21/2, 2011 at 12:49 Comment(0)
O
-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

Orotund answered 21/10, 2015 at 10:14 Comment(1)
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.Geordie

© 2022 - 2024 — McMap. All rights reserved.