What's the difference between var $x
and var x
in javascript?

- 3,336
- 5
- 26
- 29

- 15,967
- 12
- 58
- 83
-
See http://stackoverflow.com/questions/205853/why-would-a-javascript-variable-start-with-a-dollar-sign – Crescent Fresh Nov 26 '09 at 15:49
5 Answers
Nothing. People tend to use the $x syntax because it's easier to remember you're dealing with a jquery object rather than an element or an id.
In general I tend to use something similar to:
var $x = $(selector) //$x holds reference to a jquery object
var elX = document.getElementById(id); // elX hold ref to an element node
var xId = $(selector).attr('id'); //xId holds ref to an id attribute

- 17,163
- 8
- 39
- 53
-
5"xId holds ref to an id attribute" - Not really, it just holds a string... – James Nov 26 '09 at 20:14
The difference? One variable starts with $
.
And neither has anything to do with jQuery - it's just javascript.

- 235,628
- 64
- 220
- 299
One declares a variable called $x
, one declares a variable called x
. Dollar is a perfectly valid character for a variable name in JavaScript (this isn't really specifically jQuery related as far as I can see).
See "Why would a javascript variable start with a dollar sign?" for more.

- 1
- 1

- 97,747
- 36
- 197
- 212
-
You can even do i$love$$s as your variable name. But the real question is what are the differences between the $, $$ and $x native variables? – Nick Sotiros May 01 '14 at 08:43
There is no difference between two in JavaScript. $ is allowed in variable declaration in JavaScript

- 29,617
- 32
- 119
- 165
The dollar prefix is often used in Javascript for global variables. It's merely a convention - Like underscore is often used to denote a private member.

- 115,121
- 27
- 131
- 155