0

So in jQuery you have $variable and in Javascript you have variable without the $

Why do you use the $ if you can just simply declare something as var variable? Why do you need to have jQuery $variables at all?

5 Answers5

2

You can also have $variable in Javascript. jQuery is just a library that uses$ to make library and non-library functions easier to distinguish.

jett
  • 1,156
  • 1
  • 10
  • 30
2

There is no requirement to prefix jQuery variable names with $. It is merely a convention to indicate that the variable is a jQuery object/collection.

GregL
  • 32,302
  • 7
  • 58
  • 64
0

There is no need to do it and seems terrible to use it like this. You are declaring a variable with the name including the $ symbol.

Ed Capetti
  • 339
  • 2
  • 10
  • I'd rather say it is personal or team style. Nothing terrible about it at all. It may first look odd, but the benefit is clear: you immediately know this variable references a jQuery object/collection, if this is your or your teams convention, as GregL pointed out. As opposed to a raw DOM element, for instance. – Stefan Feb 11 '14 at 07:19
0

In php we must declare variable with $ sign but in javascript/jquery:

An identifier must start with $, _, or any character in the Unicode categories “Uppercase letter (Lu)”, “Lowercase letter (Ll)”, “Titlecase letter (Lt)”, “Modifier letter (Lm)”, “Other letter (Lo)”, or “Letter number (Nl)”.

The rest of the string can contain the same characters, plus any U+200C zero width non-joiner characters, U+200D zero width joiner characters, and characters in the Unicode categories “Non-spacing mark (Mn)”, “Spacing combining mark (Mc)”, “Decimal digit number (Nd)”, or “Connector punctuation (Pc)”.

source

Thus, there is no convention to use the $ sign as first letter. But the convention is to notify in javascript/jquery the $ sign is for jQuery.

Community
  • 1
  • 1
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187
0

Its just the naming convention to make you aware whether the variable, that is declared, is a DOM Element or an Object of Elements.

var variable = document.getElementById('variable');

AND

var $variable = $("#variable");
Vivek Parekh
  • 1,046
  • 9
  • 24