21

It may be a silly question but I haven't been able to find any documentations on this on the internet.

When declaring variables to use within Javascript i normally use var x = 0 but I've seen in jQuery tutorials that they use $x = 0. What is the difference of those two ?

Also, would i call those two variables the same way or do i need to use the $ mark before ? So for example : for(i=0; i < x; i++) or for(i=0; i < $x; i++)

lonesomeday
  • 215,182
  • 48
  • 300
  • 305
eski
  • 507
  • 1
  • 6
  • 20

3 Answers3

44

Your var x = 0; is fine. The only reason people sometimes use a $ with jQuery-specific variables is that it helps them remember that the variable contains the result of a call to the $() function in jQuery. The $ is actually part of the variable name, so you would use $ everywhere you referred to the variable.

So this:

var x = $(".foo");      // Find all elements with class "foo"
x.css("color", "blue"); // Make them all blue

Is exactly the same as this:

var $x = $(".foo");      // Find all elements with class "foo"
$x.css("color", "blue"); // Make them all blue

They've just put a $ at the beginning of the name.

Note: You've quoted your "jQuery" example as simply $x = 0; (without var). Be sure you always declare your variables (using var); otherwise, you're falling prey to the Horror of Implicit Globals.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
9

The dollar sign $ is not a special character in JavaScript. It is a legal character in variable naming. Here's what constitutes a legal identifier in JavaScript:

A JavaScript identifier must start with a letter, underscore (_), or dollar sign ($); subsequent characters can also be digits (0-9). Because JavaScript is case sensitive, letters include the characters "A" through "Z" (uppercase) and the characters "a" through "z" (lowercase).

Starting with JavaScript 1.5, you can use ISO 8859-1 or Unicode letters such as å and ü in identifiers. You can also use the \uXXXX Unicode escape sequences as characters in identifiers.

Some examples of legal names are Number_hits, temp99, and _name.

Some jQuery programmers (myself included) use the $ as a prefix on variable names to indicate that those variables refer to jQuery objects.

See also

Community
  • 1
  • 1
Matt Ball
  • 332,322
  • 92
  • 617
  • 683
5

No difference. The $ is just another character in JavaScript.

It just happens that jQuery users use it to signify a variable that is referencing a jQuery object. There's no requirement though.

user113716
  • 299,514
  • 60
  • 431
  • 433