8

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

CerebralFart
  • 3,281
  • 5
  • 25
  • 29
Alexsander Akers
  • 15,899
  • 12
  • 56
  • 83

5 Answers5

16

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
Steerpike
  • 16,189
  • 7
  • 38
  • 53
6

The difference? One variable starts with $.

And neither has anything to do with jQuery - it's just javascript.

Oli
  • 228,145
  • 62
  • 212
  • 294
3

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.

Community
  • 1
  • 1
Dominic Rodger
  • 94,357
  • 33
  • 195
  • 210
  • 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
1

There is no difference between two in JavaScript. $ is allowed in variable declaration in JavaScript

Xinus
  • 28,271
  • 27
  • 114
  • 164
1

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.

troelskn
  • 111,113
  • 23
  • 130
  • 153