Jonathon Faust Jonathon Faust - 1 year ago 181
Javascript Question

Why do I see JavaScript variables prefixed with $?

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,

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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download