Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery : What is the difference between "var test" and "var $test" [duplicate]

what is the difference between these statements? I know that "var $test" declares a jquery variable, but what is the difference of a jquery variable with a general javascript variable ?

like image 926
MD Sayem Ahmed Avatar asked May 21 '10 09:05

MD Sayem Ahmed


3 Answers

$test is a convention used to indicate that this variable is a jQuery object and you can call the standard functions on it while test could be a standard DOM element and you cannot call the val function on it for example.

For example:

var $test = $('#someId');
var test = document.getElementById('#someId');

You can do $test.text(); but you cannot do test.text();

like image 139
Darin Dimitrov Avatar answered Nov 02 '22 17:11

Darin Dimitrov


Nothing. No difference. $ is a valid character in a JavaScript identifier but has no special meaning. In fact, in the ECMAScript 3 specification in section 7.6 it states that

The dollar sign ($) and the underscore (_) are permitted anywhere in an identifier. The dollar sign is intended for use only in mechanically generated code.

... although events have now probably rendered that recommendation obsolete. Indeed, the recent ECMAScript 5 spec omits the final sentence.

like image 24
Tim Down Avatar answered Nov 02 '22 18:11

Tim Down


there is no difference between var $test and var test. but its always good to know what kind of data is in your variable: (for example if someone else just want to modify a function in your code without having to read, or have to console.log your vars to know whats in it)

here some examples:

var arrTest = [1, 2, a, b, c], //Array
objTest = {test: 1, test2: 2}, //Object
strTest = "test", //String
intTest = 4, //integer
$test = $("#test") //jqueryObject

but it would also work like this

var Test1 = [1, 2, a, b, c], //Array
test2 = {test: 1, test2: 2}, //Object
Test3 = "test", //String
Test4 = 4, //integer
$test = $("#test") //jquery Object

i think what confuses you is the $() form jquery.

Jquery is basically a function set on the variable name $:

var $ = function(e){ // the jquery magic }

but you can still use $somethingelse as variable.

like image 2
meo Avatar answered Nov 02 '22 16:11

meo