10

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.

Flip
  • 6,233
  • 7
  • 46
  • 75
Pete Davies
  • 1,011
  • 5
  • 18
  • 27
  • 3
    It's just to say that it is a jQuery object and that you don't need to $() it again in order to avoid unnecessary function calls. – Arnaud F. Apr 22 '11 at 09:34
  • possible duplicate of [Why would a JavaScript variable start with a dollar sign?](http://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign) – Qantas 94 Heavy May 27 '14 at 11:25

8 Answers8

18

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.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
1

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)

Will Dean
  • 39,055
  • 11
  • 90
  • 118
1

$ is a valid character in javascript variable names. It makes no difference in the snipped you posted. See this related answer.

Community
  • 1
  • 1
Jakub Januszkiewicz
  • 4,380
  • 2
  • 37
  • 54
1

Looks like a PHP developer was getting a bit tired and didn't realise he was in a javaScript code block.

psx
  • 4,040
  • 6
  • 30
  • 59
0

In JavaScript you don't need to have $ on variable names. However, to access the element using jQuery (usually by the $) you'll need the $ on the ('#selector_id') bit - i.e. $('#selector_id').

The intent of this is to denote to the programmer that the variable is a jQuery wrapper object.

Jatin Ganhotra
  • 6,825
  • 6
  • 48
  • 71
-1

In javascript $ is nothing. This is the same as add a to title (atitle). It's just a symbol you can use for names.

Emmerman
  • 2,371
  • 15
  • 9
-2

there is no purpose for $, it's just named that way. =)

Headshota
  • 21,021
  • 11
  • 61
  • 82
-3

The symbol '$' is mapped to the jQuery class. There is NO reason to prefix title with '$'.

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73