8

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

CerebralFart
  • 3,336
  • 5
  • 26
  • 29
Alexsander Akers
  • 15,967
  • 12
  • 58
  • 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
  • 17,163
  • 8
  • 39
  • 53
6

The difference? One variable starts with $.

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

Oli
  • 235,628
  • 64
  • 220
  • 299
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
  • 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
1

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

Xinus
  • 29,617
  • 32
  • 119
  • 165
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
  • 115,121
  • 27
  • 131
  • 155