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
  • 4,701
  • 5
  • 32
  • 63
Pete Davies
  • 991
  • 5
  • 16
  • 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
  • 215,182
  • 48
  • 300
  • 305
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
  • 37,648
  • 10
  • 84
  • 116
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,228
  • 1
  • 35
  • 53
1

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

psynnott
  • 3,979
  • 5
  • 27
  • 58
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,313
  • 6
  • 44
  • 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,361
  • 14
  • 9
-2

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

Headshota
  • 19,673
  • 11
  • 54
  • 77
-3

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

Richard Schneider
  • 33,296
  • 8
  • 52
  • 68