I quite often see JavaScript with variables that start with a dollar sign. When/why would you choose to prefix a variable in this way?
(I'm not asking about $('p.foo')
syntax that you see in jQuery and others, but normal variables like $name
and $order
)
$ is simply a valid JavaScript identifier. JavaScript allows upper and lower letters, numbers, and $ and _ . The $ was intended to be used for machine-generated variables (such as $0001 ). Prototype, jQuery, and most javascript libraries use the $ as the primary base object (or function).
Naming variables Variable names are pretty flexible as long as you follow a few rules: Start them with a letter, underscore _, or dollar sign $. After the first letter, you can use numbers, as well as letters, underscores, or dollar signs. Don't use any of JavaScript's reserved keywords.
Variables: A name can't start with a numeral, but a numeral can occur anywhere else. dollar sign ('$') is an illegal character.
In computer programming, a sigil (/ˈsɪdʒəl/) is a symbol affixed to a variable name, showing the variable's datatype or scope, usually a prefix, as in $foo , where $ is the sigil. Sigil, from the Latin sigillum, meaning a "little sign", means a sign or image supposedly having magical power.
Very common use in jQuery is to distinguish jQuery objects stored in variables from other variables.
For example, I would define:
var $email = $("#email"); // refers to the jQuery object representation of the dom object var email_field = $("#email").get(0); // refers to the dom object itself
I find this to be very helpful in writing jQuery code and makes it easy to see jQuery objects which have a different set of properties.
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