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?
Naming Conventions for JavaScript VariablesA variable name must start with a letter, underscore ( _ ), or dollar sign ( $ ). A variable name cannot start with a number. A variable name can only contain alpha-numeric characters ( A-z , 0-9 ) and underscores. A variable name cannot contain spaces.
It can be used easily as a replacement. Secondly it allows for the introduction of a variable without concatenating (which is what you will use it for in this lesson). This is done using ${var} to add the variable string in-line to your current string.
It's just a coding convention and it allows you to quickly reference what type the variable is later in the code.
The dollar sign ($) and the underscore (_) characters are JavaScript identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With