When/why to prefix variables with "$" when using jQuery?

JavascriptJqueryVariablesDollar Sign

Javascript Problem Overview


> Possible Duplicate:
> Why would a javascript variable start with a dollar sign?

I see people using the dollar sign in front of variables when using jQuery. Is there any reason behind this? I'm I missing something basic or is it just a common practice?

Javascript Solutions


Solution 1 - Javascript

It's a common reference to a jQuery wrapped object. It makes reading the code easier to know which variables are jQuery wrapped.

//Item has been "cached" for later use in the script as a jQuery object.
var $item = $(this);

Solution 2 - Javascript

For me a common practice is this:

If a variable is private I use an underscore like this:

(function(){
var _foo = "bar";
})()

If it's public I'll use no underscore:

var foo = "bar"

And if it's a jQuery selector I'll use the $:

var $foo = $('bar');
//then you can access it like this
$foo.attr('id')

It's just coding convention and it allows you to quickly reference what type the variable is later in the code.

Solution 3 - Javascript

Many people using jQuery will prefix variables that contain a jQuery object with a $, so that they are easily identified. Consider this example:

var $img = $(".someclass span.otherclass img");
/* somewhere later in the code */
$img.bind("click", function() {/*...*/});

Solution 4 - Javascript

In my experience this is just a readability. Some developers like to prefix their variables so that they are easy to spot. It could also be a PHP habit creeping it's way in to Javascript.

Solution 5 - Javascript

Dollar signs in code that uses JQuery commonly means that the variable in question is a jQuery variable (an object wrapped by jquery).

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
QuestionelclanrsView Question on Stackoverflow
Solution 1 - JavascriptScott HarwellView Answer on Stackoverflow
Solution 2 - JavascriptlocrizakView Answer on Stackoverflow
Solution 3 - JavascriptsanmaiView Answer on Stackoverflow
Solution 4 - JavascriptsupajbView Answer on Stackoverflow
Solution 5 - JavascriptMarino ŠimićView Answer on Stackoverflow