Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Why prepend a $ to variable name?

Tags:

jquery

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.

like image 874
Pete Davies Avatar asked Apr 22 '11 09:04

Pete Davies


People also ask

What is the significance of in front of a variable name?

It's just a coding convention and it allows you to quickly reference what type the variable is later in the code.

What does the in front of a JavaScript variable mean?

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

What does before variable name mean JavaScript?

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.

What is '$' in JavaScript?

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.


Video Answer


2 Answers

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.

like image 100
lonesomeday Avatar answered Nov 16 '22 04:11

lonesomeday


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)

like image 39
Will Dean Avatar answered Nov 16 '22 04:11

Will Dean