462

The code in question is here:

var $item = $(this).parent().parent().find('input');

What is the purpose of the dollar sign in the variable name, why not just exclude it?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Keith Donegan
  • 26,213
  • 34
  • 94
  • 129
  • 4
    possible duplicate of http://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign – DisgruntledGoat Apr 15 '10 at 15:11
  • [ttony21's answer][1] is wrong stating that there are no types in Javascript, cf. [official documentation][2] [1]: http://stackoverflow.com/questions/846585/can-someone-explain-the-dollar-sign-in-javascript/846594#846594 [2]: http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf – anddam Mar 11 '11 at 08:49
  • 1
    Possible duplicate of [Why would a JavaScript variable start with a dollar sign?](https://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign) – Ken Nov 19 '17 at 11:17

12 Answers12

455

A '$' in a variable means nothing special to the interpreter, much like an underscore.

From what I've seen, many people using jQuery (which is what your example code looks like to me) tend to prefix variables that contain a jQuery object with a $ so that they are easily identified and not mixed up with, say, integers.

The dollar sign function $() in jQuery is a library function that is frequently used, so a short name is desirable.

Emery Lapinski
  • 1,572
  • 18
  • 26
cobbal
  • 69,903
  • 20
  • 143
  • 156
  • 98
    Note: By default, jQuery uses "$" as a shortcut for "jQuery". This has some effects on the use of other Javascript libraries. See http://docs.jquery.com/Using_jQuery_with_Other_Libraries – Thimmayya Nov 07 '09 at 01:27
  • 20
    In other words, $ is comparable to any acceptable symbol in variable/function names. Doing `var $=function(){}` is very same as doing `var a=function(){}`. – F-3000 Dec 07 '13 at 12:32
  • 31
    Thimmayya your comment "By default, jQuery uses "$" as a shortcut for "jQuery"" should be in bold letters at the top of every page on Jquery's website, Their examples are horribly documented. – RustyH Jun 25 '14 at 21:59
  • What about when $ is specified as a function parameter? I am looking at some code like `jQuery(document).ready(function($){`... Then the $ is used inside the function implementation. – still_dreaming_1 Sep 16 '16 at 16:32
  • Oh, I think I get it. It is just the name of the parameter / variable, which has no special meaning outside of maybe a convention. Then the variable is referenced / used in the implementation. – still_dreaming_1 Sep 16 '16 at 16:35
  • @still_dreaming_1, you're wrong. I just started using Angular.js, and I decided to call the parameter to my function `scope` instead of `$scope`. It failed to work until I tacked the dollar sign back on. I have no idea what's going on here, but that dollar sign has to mean *something*. – Throw Away Account Feb 17 '17 at 22:15
  • 4
    @ThrowawayAccount3Million It's just part of the name. In the case of `$scope` the $ is one of the characters in that name. Just as if you take off the `e` at the end of `$scope`, it won't work, so taking of the `$` will also not work. In the case that you see something like `$( "a" ).addClass( "test" )`, the dollar sign is the entire name of whatever that is. – still_dreaming_1 Feb 20 '17 at 14:48
  • If JavaScript functions are lexically scoped, then how does it matter what you name the argument to your function? Since `$scope` is the parameter to a function you create, it shouldn't matter what you name it. – Throw Away Account Mar 01 '17 at 11:43
  • I think the question is pretty old, at that time didn't exist ECMAScript6. The meaning of $ as in the explanation / answere of @UpTheCreek is also very important. https://stackoverflow.com/a/41167804/3408530 – NicDD4711 Mar 12 '19 at 15:00
  • Hi @cobbal; maybe this could be a separate question, but does the $ symbol have the same semantics in TypeScript? – Orco May 19 '21 at 21:08
  • @Orco The `$` character has _no_ special semantics in JavaScript or TypeScript. It is treated as just another "alphabetic" character, like `_`. Any semantics it may have are simply determined by how it is used in the code you write or import. – Michael Geary Dec 03 '22 at 23:05
82

In your example the $ has no special significance other than being a character of the name.

However, in ECMAScript 6 (ES6) the $ may represent a Template Literal

var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.
UpTheCreek
  • 31,444
  • 34
  • 152
  • 221
  • 1
    "*the $ has no special significance other than being a character of the name.*" it **does** have special significance. It indicates that the value for that variable is a jQuery wrapped object. It's a type of [Hungarian notation](https://en.wikipedia.org/wiki/Hungarian_notation). Thus you know how to operate with the value purely by the naming convention. – VLAZ Jun 30 '21 at 14:36
  • 4
    @VLAZ Don't confuse language syntax with library conventions. Neither the question nor this answer mention jQuery, but only JavaScript - and in JavaScript, the `$` sign does not have any special meaning, besides the template literal in ES6. – Andreas Fester Apr 14 '22 at 08:44
  • 1
    @AndreasFester "*Neither the question nor this answer mention jQuery*" the question most certainly shows using jQuery code. It may not *mention* it but *the usage is consistent with how jQuery is used*. The question doesn't *need* to mention jQuery if that's what it actually shows. OP is *asking* about it because they *don't know it*. – VLAZ Apr 14 '22 at 08:50
40

The dollar sign is treated just like a normal letter or underscore (_). It has no special significance to the interpreter.

Unlike many similar languages, identifiers (such as functional and variable names) in Javascript can contain not only letters, numbers and underscores, but can also contain dollar signs. They are even allowed to start with a dollar sign, or consist only of a dollar sign and nothing else.

Thus, $ is a valid function or variable name in Javascript.

Why would you want a dollar sign in an identifier?

The syntax doesn't really enforce any particular usage of the dollar sign in an identifier, so it's up to you how you wish to use it. In the past, it has often been recommended to start an identifier with a dollar sign only in generated code - that is, code created not by hand but by a code generator.

In your example, however, this doesn't appear to be the case. It looks like someone just put a dollar sign at the start for fun - perhaps they were a PHP programmer who did it out of habit, or something. In PHP, all variable names must have a dollar sign in front of them.

There is another common meaning for a dollar sign in an interpreter nowadays: the jQuery object, whose name only consists of a single dollar sign ($). This is a convention borrowed from earlier Javascript frameworks like Prototype, and if jQuery is used with other such frameworks, there will be a name clash because they will both use the name $ (jQuery can be configured to use a different name for its global object). There is nothing special in Javascript that allows jQuery to use the single dollar sign as its object name; as mentioned above, it's simply just another valid identifier name.

thomasrutter
  • 114,488
  • 30
  • 148
  • 167
  • 1
    You can noconflict the jQuery object with this `var $j = jQuery.noConflict();` now $j is the jQuery object. – Justin Liu Jun 12 '20 at 23:43
38

The $ sign is an identifier for variables and functions.

https://web.archive.org/web/20160529121559/http://www.authenticsociety.com/blog/javascript_dollarsign

That has a clear explanation of what the dollar sign is for.

Here's an alternative explanation: http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html

andrewsi
  • 10,807
  • 132
  • 35
  • 51
AlbertoPL
  • 11,479
  • 5
  • 49
  • 73
  • 2
    Javascript does have types; and in any case, how is the dollar sign even related to that? It's just a character that happens to be a legal identifier in Javascript. – Erik Kaplun Nov 10 '11 at 22:02
  • 12
    I'm not sure I would call that link a "clear" explanation. Does it really take 6+ paragraphs to explain that $ is simply a valid character when defining function and variable names? – Slight Mar 20 '15 at 20:28
  • 1
    Looks like the first link is working again. I have to agree with @Slight that alternative explanation is terrible. – Sander Garretsen Oct 20 '15 at 14:27
  • The sample code in the link is quite easy to understand. Awesome! – 蔡宗容 Mar 05 '19 at 07:19
15

Dollar sign is used in ecmascript 2015-2016 as 'template literals'. Example:

var a = 5;
var b = 10;
console.log(`Sum is equal: ${a + b}`); // 'Sum is equlat: 15'

Here working example: https://es6console.com/j3lg8xeo/ Notice this sign " ` ",its not normal quotes.

U can also meet $ while working with library jQuery.

$ sign in Regular Expressions means end of line.

Vasyl Gutnyk
  • 4,813
  • 2
  • 34
  • 37
  • 1
    This use of the dollar sign did not appear in the question. Is this the result of this answer being moved here from elsewhere? – thomasrutter Aug 12 '21 at 01:22
6

I'll add this:

In chromium browser's developer console (haven't tried others) the $ is a native function that acts just like document.querySelector most likely an alias inspired from JQuery's $

Sodj
  • 846
  • 11
  • 18
5

When using jQuery, the usage of $ symbol as a prefix in the variable name is merely by convention; it is completely optional and serves only to indicate that the variable holds a jQuery object, as in your example.

This means that when another jQuery function needs to be called on the object, you wouldn't need to wrap it in $() again. For instance, compare these:

// the usual way
var item = $(this).parent().parent().find('input');
$(item).hide(); // this is a double wrap, but required for code readability
item.hide(); // this works but is very unclear how a jQuery function is getting called on this 

// with $ prefix
var $item = $(this).parent().parent().find('input');
$item.hide(); // direct call is clear
$($item).hide(); // this works too, but isn't necessary

With the $ prefix the variables already holding jQuery objects are instantly recognizable and the code more readable, and eliminates double/multiple wrapping with $().

SNag
  • 17,681
  • 10
  • 54
  • 69
4

No reason. Maybe the person who coded it came from PHP. It has the same effect as if you had named it "_item" or "item" or "item$$".

As a suffix (like "item$", pronounced "items"), it can signify an observable such as a DOM element as a convention called "Finnish Notation" similar to the Hungarian Notation.

Yushin Washio
  • 675
  • 8
  • 12
Claudiu
  • 224,032
  • 165
  • 485
  • 680
2

Here is a good short video explanation: https://www.youtube.com/watch?v=Acm-MD_6934

According to Ecma International Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1). The Unicode identifier grammar is based on both normative and informative character categories specified by the Unicode Standard. The characters in the specified categories in version 3.0 of the Unicode standard must be treated as in those categories by all conforming ECMAScript implementations.this standard specifies specific character additions:

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

Further reading can be found on: http://www.ecma-international.org/ecma-262/5.1/#sec-7.6

Ecma International is an industry association founded in 1961 and dedicated to the standardization of Information and Communication Technology (ICT) and Consumer Electronics (CE).

Nomis
  • 437
  • 1
  • 4
  • 13
2

"Using the dollar sign is not very common in JavaScript, but professional programmers often use it as an alias for the main function in a JavaScript library.

In the JavaScript library jQuery, for instance, the main function $ is used to select HTML elements. In jQuery $("p"); means "select all p elements". "

via https://www.w3schools.com/js/js_variables.asp

D. Schreier
  • 1,700
  • 1
  • 22
  • 34
Aaron A.
  • 59
  • 1
  • 6
0

I might add that using it for jQuery allows you to do things like this, for instance:

$.isArray(myArray);
0
    let $ = "Hello";
    let $$ = "World!";
    let $$$$$$$$$$$ = $ + " " + $$;
    alert($$$$$$$$$$$);

This displays a "Hello World!" alert box.

As you can see, $ is just a normal character as far as JavaScript identifiers or variable names go. In fact you can use a huge range of Unicode characters as variable names that look like dollar or other currency signs!

Just be careful as the $ sign is also used as a reference to the jQuery namespace/library:

$("p").text("I am using some jquery");

// ...is the same as...

jQuery("p").text("I am using some jquery");

$ is also used in the new Template Literal format using string interpolation supported in JavaScript version ES6/2015:

var x = `Hello ${name}`;
Stokely
  • 12,444
  • 2
  • 35
  • 23