Why use $ in javascript variable names?

Possible duplicates:
Why does javascript variable start with a dollar sign?
JQuery: What is the difference between "var test" and "var $ test"

What is the difference between these two ways to initialize variables?

var $val = 'something' OR var val = 'something' 

as I see, they are one and the same.

Maybe in this case $ is only part of the name in the variable? (in this case it will become meaningless: /)

thank

+44
javascript jquery
Jul 29 '10 at 9:02
source share
5 answers

$ in the variable name is only part of the name , but the convention is to use it to run variable names when a variable represents a jQuery object.

 var $myHeaderDiv = $('#header'); var myHeaderDiv = document.getElementById('header'); 

Now, in your code, you know that $myHeaderDiv already a jQuery object, so you can call jQuery functions:

 $myHeaderDiv.fade(); 

To get a jQuery variable from a DOM variable:

 var $myHeaderDiv = jQuery(myHeaderDiv); //assign to another variable jQuery(myHeaderDiv).fade(); //use directly //or, as the $ is aliased to the jQuery object if you don't specify otherwise: var $myHeaderDiv = jQuery(myHeaderDiv); //assign $(myHeaderDiv).fade(); //use 

To move from a jQuery variable to a DOM variable.

 var myHeaderDiv = $myHeaderDiv.get(0); 
+87
Jul 29 '10 at 9:04 on
source share

You're right. $ is part of the variable name.
This is not perl or PHP :)

+11
Jul 29 '10 at 9:03
source share

There are 28 letters in the alphabet with regard to JavaScript. az, _ and $. Anywhere where you can use JavaScript, you can use $ as a letter. (<c> Fellgall @ http://www.webdeveloper.com/forum/showthread.php?t=186546 )

In your example, $ val and val will be two different variable names.

+5
Jul 29 '10 at 9:03
source share

No real difference.

Commonly used to mean a variable containing jquery or another javascript object, as they may have a shorthand $ function.

Easier to identify content type.

+5
Jul 29 '10 at 9:04 on
source share

syom - in my case, I use the $ prefix to indicate that it is the variable referenced by jquery. This is purely part of the variable, not a reserved character.

makes it easy to identify with long runs of code.

Jim

+3
Jul 29 '10 at 9:03
source share



All Articles