views:

129

answers:

3

This is sort of a meta-question. Many snippets of JavaScript I've seen here on SO are named with a dollar sign prefix (for example, $id on the second line of the snippet shown in this question). I'm not referring to jQuery or other libraries. I am well aware that this is valid, but it seems awkward to do when not necessary. Why do people name their variables like this? Is it just familiarity with a server-side language like PHP carrying over into their JavaScript code?

I thought perhaps it was to identify a variable as being a jQuery object, for example when you save the result of a selection to a variable in order to eliminate duplicate selections later on, but I haven't seen any consistent convention.

+12  A: 

Syntactically, the dollar sign itself means nothing -- to the interpreter, it's just another character, like _ or q. But a lot of people using jQuery and other similar frameworks will prefix variables that contain a jQuery object with a $ so that they are easily identified, and thus not mixed up with things like integers or strings. You could just as easily adopt the same convention by prefixing such variables with jq_ and it would have the same effect.

In effect, it is a crude sort of Hungarian notation.

John Feminella
`In effect, it is a crude sort of Hungarian notation.` Luckily, I don't see much JavaScript written like `var strHippo = "hippo";`.
Jonathon
its not hungarian notation at all...
Matt Briggs
+3  A: 

I will sometimes prefix a variable name with $ to indicate that it is a jQuery-wrapped element (most often when I'm using $(this) in a function a lot, I will assign that to $this).

Part of where the lack of convention may come from is people copy-pasting code together that uses different conventions, thus producing inconsistent code.

Also, sometimes (rarely I hope) people who program in PHP a lot will put $'s at the beginning of their variable names out of habit.

pib
Indicating saved jQuery objects with $ seems like a decent practice. It's just been baffling when I see it on a variable being used to store a String or some other unrelated type.
Jonathon
Definitely, it really makes no sense to arbitrarily use `$`s in some places and not in others. Though it would be weird to use it everywhere, too.
pib
+2  A: 

I suspect the person in that example was just copying the jQuery pattern, or is used to PHP/Perl, without really understanding that it isn't necessary and has no special meaning.

However, I have seen [experienced] programmers use it for variable names that are reserved keywords, such as $class or $this. Or even for globals. It's really a personal preference more than anything, in that case.

Brad G.
People copying jQuery without knowing better seems likely.
Jonathon