I am trying to learn jQuery and I came across this line in an example.
var $title = $(tag).attr('title');
Can someone please tell me what the prepended $ is for in $title
.
The example seems to work fine if I replace $title
with just title
.
I understand this is probably a stupid question but it is a waste of time googling for "purpose of $"
Many thanks.
It's just a coding convention and it allows you to quickly reference what type the variable is later in the code.
on Dec 6, 2017. That's the logical "not" operator. It means "the opposite of". So if the variable contains "false", then putting "!" in front will make the result "true".
May 4, 2012 at 6:05. Sometimes, the $ before a variable name is to indicate that it is a jQuery object and not, say, a raw DOM element. That is, you might say var $this = $(this) with the $ in front to indicate that it's a jQuery object. On the other hand, you might have var element = document.
Updated on July 03, 2019. The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.
It doesn't "mean" anything. The $
character is a legal character in Javascript variable names.
However, there is a convention (which isn't universal) of using $
as a prefix to any variable that points to a jQuery selection.
You give the example:
var $title = $(tag).attr('title');
This is a bad use of the $
character, according to this convention. $title
is a string, not a jQuery selection.
This would be a correct use of the character:
var $el = $(tag);
var title = $el.attr('title');
Otherwise, a big reason for the prevalence of the $
character is that it is mandatory in PHP, and there is a big overlap between jQuery and PHP programmers.
I think people use it as a convention for 'things I looked up with jQuery that I want to hold onto without needing to look up again'.
The one you see most often is var $this = $(this)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With