Can someone explain the dollar sign in Javascript?
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?
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.
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
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 start with a dollar sign.
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.