Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would a JavaScript variable start with a dollar sign? [duplicate]

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)

like image 951
Ken Avatar asked Oct 15 '08 18:10

Ken


People also ask

What does '$' mean in JavaScript?

$ 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).

Can JavaScript variables start with dollar sign?

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.

Can a variable start with dollar?

Variables: A name can't start with a numeral, but a numeral can occur anywhere else. dollar sign ('$') is an illegal character.

What is a variable with a dollar sign?

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.


1 Answers

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.

like image 138
jonstjohn Avatar answered Oct 21 '22 10:10

jonstjohn