Why use $ (dollar sign) in the name of javascript variables?

JavascriptJquery

Javascript Problem Overview


> Possible Duplicates:
> Why would a javascript variable start with a dollar sign?
> JQuery : What is the difference between “var test” and “var $test”

What is the difference between this two ways of initializing variables?

var $val = 'something'

     OR

var val = 'something'

as I see they are the same thing.

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

Thanks

Javascript Solutions


Solution 1 - Javascript

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

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

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

$myHeaderDiv.fade();

###To get from the DOM-variable to the jQuery 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 get from the jQuery variable to the DOM-variable.

var myHeaderDiv = $myHeaderDiv.get(0);

Solution 2 - Javascript

You are correct. $ is a part of the name of the variable.
This is not perl or PHP :)

Solution 3 - Javascript

There are 28 letters in the alphabet as far as JavaScript is concerned. a-z, _ and $. Anywhere you can use a letter in JavaScript you can use $ as that letter. (<c> Fellgall @ http://www.webdeveloper.com/forum/showthread.php?t=186546)

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

Solution 4 - Javascript

No real difference..

It is usally used to signify a variable holding a jquery or other javascript framework object, because they can have shorthand $ function..

It is just easier to identify the type of the contents..

Solution 5 - Javascript

syom - in my case, i use the $ prefix to indicate that it's a variable that is referenced by jquery. It's purely a part of the variable and not a reserved character.

keeps it easy to identify in long code runs..

jim

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSimonView Question on Stackoverflow
Solution 1 - JavascriptKonerakView Answer on Stackoverflow
Solution 2 - Javascriptthe_drowView Answer on Stackoverflow
Solution 3 - JavascriptMāris KiseļovsView Answer on Stackoverflow
Solution 4 - JavascriptGabriele PetrioliView Answer on Stackoverflow
Solution 5 - Javascriptjim tollanView Answer on Stackoverflow