Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at cf.Objective() 2014 (Bloomington, MN) with:

Using $Variable In jQuery Code Is Just Hungarian Notation

By Ben Nadel on

I have been reading a lot about jQuery over the past few months and one thing that I have noticed is the growing prevalence of prepending jQuery variables with the dollar sign, "$". For example, inside of an event handler callback, one might create a jQuery wrapper for the "this" reference as follows:

  • .click(function(){
  • var $this = $( this );
  • });

I understand the intent of this - to denote to the programmer that the variable is a jQuery wrapper object. I used to do something similar, only I chose the prefix "j" (as in "jQuery") rather than the dollar sign:

  • .click(function(){
  • var jThis = $( this );
  • });

I started doing this because I looked at the jQuery container as a "data type," just as we might philosophically look at any class. As such, when I was using a lot of Hungarian notation, I prefixed it with something that would indicated its data type. "jThis" was no different to me than "strName" or "blnIsTrue" or "fnDoSomething()" - it just lent more insight into the data being referenced by the variable.

Hungarian notation is comforting - I know, I used it for years and years. But months ago, I realized that it was causing too many inconsistencies in my code. As such, I decided to try and drop that naming-approach and adopt the more widely held headless-camel-case notation. While headless-camel-case did not lend as much visual insight into the type of data being referenced, I came to understand that that was purely an emotional view; and in fact, I quickly came to find headless-camel-case the right choice for my code.

jQuery is a relatively new "technology" for a lot of people; and, any time that something is new, I think we create emotionally-driven constructs to comfort ourselves. As we feel our way through the jQuery library and try to get a grasp on how to best integrate it with our other Javascript code, there is certainly an emotional satisfaction in knowing that the jQuery variables are singled out and clearly delineated. Javascript code, especially to HTML-programmers, is complicated enough as it is, and this $-prefix helps to maintain sanity.

I say all this only to point out that the jQuery object is just another data type (like an Array) and the use of the "$" prefix is just another form of Hungarian notation. I see no reason that anyone should ever think of the "$" prefix as any sort of "best practice"; and, I would say that choosing more insightful variable names removes the need for any data-type-prefixing at all.

As a thought experiment, take a look at some of these variable names as defined inside of an event handler callback:

  • .click(function(){
  • // This is the element that triggered the event.
  • var trigger = $( this );
  •  
  • // This is the element that was target of the event.
  • var target = $( this );
  •  
  • // This is the container element that captured the event
  • // (if it was on a DIV or UL or something).
  • var container = $( this );
  • });

Now, I'm not saying that these variable names are all equally insightful - it depends on the situation. But, I do honestly believe that all of these variable names offer more insight than "$this".

At the end of the day, there is no objectively right choice in variable naming conventions; it comes down to what you are most comfortable with and what makes you most efficient. But, I urge you take a moment and ask yourself if your choices are well thought out, or if they are based purely on emotional reactions.




Reader Comments

I do tend to use the "$" to prefix any variable that represents a jQuery object (as opposed to a string or numeric variable), but I also try to make the variable name descriptive. For example, if I wrote a click event handler for a hyperlink and I wanted to copy the clicked hyperlink to a variable, I'd do this:

var $clickedLink= $(this);

...as you said, it comes down to personal preference, especially if you're coding solo and the primary audience for your code is a later version of yourself. ;)

Reply to this Comment

I think it's worth mentioning that some people use the "$" to avoid conflicts between jQuery and another framework like mootools.

e.g. (function($){

This is sometimes referred to as "no conflicts mode", but basically it avoids name clashing.

Reply to this Comment

I'm right there with you Ben; I held strongly to Hungarian notation for a long time, but abandoned it because it looses meaning in loosely typed languages such as CF and JS, and in strongly typed languages, the compilers wont let you make a mistake any way.

Strangely, I still use the $ prefix in one situation: var $this = $(this). The only reason I do is because I know that setting var this = $(this) could cause problems, and I think that the word "this" still describes what I'm working with most accurately, even if its now wrapped in jQuery. For anything else, I just set the variable like: var element = $(event.target). I guess I just find "this" important enough to keep around.

Reply to this Comment

i think it's worth pointing out - as the yayQuery guys did in their podcast, which, i believe, this post of yours kind of comes from - that $ as prefix for a var name IS just that, a prefix.

the growing prevalence of its use is, to a certain degree at least, due to more and more developers adopting jQuery as their main tool. many of these developers are relatively new to js in general, diving deeper into it now that jQuery made it easy and fun.
the help, knowledge, examples and tricks these new jQuery users get are from various great blogs like yours, Ben, where they see jQuery gurus using variable names like $this and $that. at least some of these jQuery newcomers do assume that this is some required naming convention, especially since they see $ used to denote jQUery namespace...

Azadi

Reply to this Comment

@Sam,

I am sorry if I was not clear in my explanation; I was not referring to the use of the "$" for the jQuery alias - I am all for that, especially in passing it to the "ready" function as you have demonstrated. What I was referring to my post was the use of the "$" as a variable prefix, as in "$table".

@Azadi,

Yes, it was mentioned on YayQuery, but it has also been mentioned elsewhere explicitly, including the "jQuery Cookbook" which I am currently reading.

But, I think you and I are hitting on the same point - for people who are new to Javascript, let along jQuery itself, I think there is certain emotional comfort level with the "$" prefix - like diving your food up into compartments on a cafeteria tray :)

Reply to this Comment

I totally agree that Hungarian Notation is something that should not be used.

However, I view the $ prefix as something slightly different. Hungarian notation had its hay-day primarily in type-safe environments where you needed to know the type of a variable for casting-sake (since the editor's weren't smart, it was comment to make your variable names smart). The main area where I found the Hungarian Notation problematic is it logically tightly bound your variable to a specific type. For example, iItemCount would refer to an integer or lstContacts would be a listbox element. The problem with those notations is that what happens when you need to expand your ItemCount to a long or use some sort of Grid instead of a listbox? Do you have to go and rename the variables to match the new types? Either you changed the variable name to match (which is annoying) or you don't change the names and confuse future programmers looking at your code (or yourself for that matter).

Prepending the $ to jQuery variables doesn't necessarily fall into one of the above scenarios. Other than changing your JavaScript library I'm not certain where the prepended $ could come into trouble. And if you changed your JavaScript library (to MooTools or YUI) then you would probably have much bigger changes on your hand.

Anyway, I am fine w/ the prepended $ and although technically it does indicate the type of variable (as Hungarian Notation does), I find that this technique has value without introducing the pitfalls of Hungarian Notation.

That is what I am thinking now. Who knows, it might change in the near future ;)

Thanks for your blog post. I enjoyed thinking about this.

Reply to this Comment

@Elijah,

By your argument, however, would it not also follow that people would benefit from Hungarian Notation in other situations where the data type is not going to change?

For example, a flag such as "isVisible"; something like that (prefix or not) should clearly always be a truthy/flasy value. As such, why not just throw "bln" before it - blnIsVisible?

If there is any advantage to prefixing with "$", I believe it to be purely emotional. Now, I am not saying that that is *wrong*. Lots of things we do are for emotional reasons; and, as long as we are consistent, things are great.

I am really only trying to say that at the end of the day, a jQuery object is just a data type, like an Array or an Object, and nothing more. If you want to put "$" before it because it helps you, understand that it is for data-type-visibility only and should not be thought of as "best practice" (or, really, any different from any other data-type-prefix).

Reply to this Comment

I do agree that it's just Hungarian Notation. I also agree it can be helpful to use. When jQuery was new to me, it helped to use the $ prefix to know that it was a jQuery "wrapped" object but now after using jQuery quite a bit it's just noise to me.

My stance is that if you need to name variables with "tricks" to remember them later you're probably writing methods that are too long. Small concise methods are preferred and shouldn't have too many variables. Keep them small and you won't need these types of tricks.

Reply to this Comment

@Ben,

Good point about the boolean variable. That would stink!

So... although I like consistency, maybe this is my one exception to the rule ;)

Thanks for responding to my comment and helping me think through it a little more.

I am waiting for my copy of the jQuery Cookbook. Maybe I'll have some more insight after reading that as well.

I hope to meet you one day. Enjoy the blog posts.

Reply to this Comment

@Elijah,

I love a good conversation, and I'm pumped you're enjoying the posts. And, just for re-disclosure, I am coming to this conversation as a "born-again-camel-case" person :) I haven't used a typed language in forever, but even so, I was a heavy user of Hungarian Notation for years (both in ColdFusion and in Javascript). Heck, I even use the $-prefix approach.

But, as someone who has recently tried dropping HN and found headless-camel-case to afford much more consistent code, I guess I have the zeal of a new convert.

Reply to this Comment

I prepend all my jquery variables with a dollar, simply so while I scan over my code, I can easily see what is a "selector" and what is simply a variable.

eg

$("div").click(function(){ ... });

that's quite easy to spot as a selector while scanning through chunks of code, while

var div = $("div");
div.click(function(){ ... });

is visually harder to spot, but as the dollar symbol stands out, it keeps things easy to see.

var $div = $("div")
$div.click(funcion(){ ... });

Reply to this Comment

@Liam,

To play devil's advocate, I would have to ask why a jQuery selector variable is any more important than other variables? Or rather, why are you scanning code looking for jQuery selector variables?

Reply to this Comment

Interesting read, Ben. I agree that its only usage would be for emotional reasons, but that's not a bad thing. You mentioned that you don't use the $-prefix approach anymore; is there a specific reason why, other than the fact that it technically conforms to the Hungarian notation method?

As Elijah referenced, there can be downsides to H-notation, but I don't necessarily see any potential negatives with using "$" as a prefix, if it makes you feel more comfortable.

As I see it - if it makes your code more readable, then who cares. :)

--

Great article, Ben. Would you like to write for Nettuts+ sometime? We'd love to have you as a guest author. If interested, email me at nettuts@tutsplus.com or tweet me at @nettuts.

Reply to this Comment

"I would have to ask why a jQuery selector variable is any more important than other variables? Or rather, why are you scanning code looking for jQuery selector variables?"

Because it reminds you that you have access to jQuery's methods, when you come back to the project months later. At least that's why I do it.

Reply to this Comment

@Jeffrey,

At the end of the day, I strive for consistency. That's why I have several times stood back and completely re-evaluated all aspects of my coding approaches and altered my coding methodologies. I have an (admittedly) emotional need to be able to concretely explain why I make all my coding choices. As such, I stopped using the "$" prefix simply because it was inconsistent and had no valid (for me) use cases.

Would definitely love to write for 'tuts. I'll shoot you an email, thanks :)

Reply to this Comment

@Jeffrey,

True - but ultimately that is why any Hungarian Notation is used. I used to use the prefix, "arr" to remind it was an Array and that I had access to .slice(), .splice(), and .join() method. Similarly, I used to use "obj" prefix to remind it was an Object and that I had access to name-value pairs and the for-in construct.

... any argument that is based on data-insight becomes less "effective" when it is not consistent. Especially when I would bet that most people's Javascript breaks on non-jQuery errors.

Reply to this Comment

@Jeffrey,

Something else to think about to denote it is a selector is to give it a more meaningful name. In your example there it does not limit it to a specific div or a set of div. It selects all divs. Thus wouldn't a more concise name than "div" be appropriate rather than prefixing it with the $

Reply to this Comment

My distant background is with strongly typed languages and while I think the opposite is bad, I can enjoy the freedom. Since I make few serious mistakes related to the type of a variable, I've adjusted quite well. What I really don't like are poorly defined functions, which is most all in Coldfusion from Adobe. I like Coldfusion, just not the documentation.

I do not prefer more than light use of Hungarian Notation although when used sparingly for some circumstances, it can work fine. Heavy use creates mud. So I think I'm very much in agreement with Ben on this, if not completely. Although, I do not see the use or not use of HN as emotional (for me and I suspect for many people) unless one mandates that others do as I do or refuses to consider alternate ways of doing things - and even then it may not be emotional, but one could only be considering immediate expediency. And if you are not always considering alternate ways of doing things, that can bring death in programming.

I remember (way back) when the standard for C functions started requiring that the formal parameters be prefaced by the variable type instead of allowing the argument types to be declared on subsequent lines below. I prefered the old way because I found it easier to read the code. But one can't defeat the standards committees. And now we have new languages and the type declarations have gotten thrown out!!! I think mostly in the name of making the languages easier for beginners (though I doubt this was any concern for javascript).

Reply to this Comment

Here's why I like the $ prefix:

var table = document.getElementById("#tableId");
var $table = $("#tableId");

I often have variables for both the actual DOM element and for a jQuery equivlent--which happens a lot in plug-in development.

So, while I could do things like:

var tableAsDom = document.getElementById("#tableId");
var tableAsJQuery = $("#tableId");

I like the $ prefix better. It's shorter and just as descriptive to me.

(NOTE: The above example is just to illustrate how you might have references to both a jQuery and DOM object which point to the same thing.)

Reply to this Comment

@Dan,

Having two values that are different only in data-type is definitely a very real situation. Often times when that happens to me, I pick one way or the other - usually based on the one that I am bound to use more often. So, for example, using your code, I would go this way:

var tableNode = document.getElementById( "#tableId" );
var table = $( tableNode );

Here, both values represent a table in some way; however, I have chosen to use the jQuery-style one with the shorter name, and the raw, node-type one in the more descriptive way.

Reply to this Comment

Interesting post Ben! I am very wishy-washy on whether I agree with my tendency to use the $ prefix. I think I rationalized my thoughts best in one of the recent podcasts, though, and I think I can still stick by that. Dan touches on the same point that I bring up, and while I see that

tableNode and table

are a good alternative to $ prefix notation, I have to say that it seems just like reverse hungarian notation on the `tableNode` variable.

That's fine, and it works, and if you like it better because of consistency, then I say go for it. However, I don't think anything is gained from that approach, and I can see confusion coming up in future cases when you have ONLY a dom node and so you don't add the 'Node' postfix to the end. Then consistency is thrown out the window and you are back where you started.

My argument is that we have created a new type of notation. I called it SUPER notation in the podcast, but I think I'll retract and call it 'wrapper notation.'

The fact is, we have two of the same object. In one case we have this extra api on top of it, and in the other case its raw. I called the $ prefix a super-identifier because A) it looks like an 'S' for 'super' and B) because it really described just a beefier version of the same object with a slightly different api.

I'm not sure there is ever a case where you can remain consistent and not describe the type of one of the objects. Its not a matter of hungarian notation.

If you extended this to the real world...

Say you always carried your glock 9mm with you when you went to certain parts of town, but other times you didn't. If I had to reference you in a program. I would call you:

var benNadel = new Person();

I wouldn't go with `prsnBenNadel` or anything weird and static like that.

But if I had to reference you in the times you were carrying a gun, I would do something like:

var gunBenNadel = new Gunman(benNadel);

or maybe:

var benNadelWithAGun = new Gunman(benNadel);

I think either way, it's logical to describe you, not as `gunmanBenNadel` but just as something that says, 'hey this is simply ben nadel with a few extra tricks up his sleeves` (an extended api if you will...).

So that's my way-too-drawn-out-reason for thinking that $ is ok. While you can think that it just means `jqueryobjectThis` - I think 'wrapper notation' fits a litter better, which would describe that as `just 'this' with a little bit extra on top.`

The key is that this is only applies when one variable encapsulates an _instance_ of another variable, since they actually refer to the same piece in memory.

Reply to this Comment

@Alex,

There are always going to be cases in any programming language where the only difference between two variables is the data type they represent. For instance, when I stream serialized data back ColdFusion to the client, I first convert it to binary. So, I might have code like this (pseudo code):

<cfset responseData = serializeJSON( someOjbect ) />

<cfset responseBinary = toBinary( responseData ) />

Yes, these two variables are different only in the type of data they represent, and the name reflects that. However, this is an extremely rare case. To say that one or two outliers defines how all variables would be named, I believe is not desired.

I think if we take a step back and think about the code that we write, how often do we actually have variables in a single function that are different only in representation?

Let's be honest - in Javascript, that happens very rarely for me. If I'm going to be creating jQuery objects, most likely, I'm gonna be using jQuery to collection them - I'm not going to manually grab some intermediary raw-node set from the DOM and THEN wrap it in a jQuery collection.

I would consider your gunman example to be one of the outliers. If you take a nod from the Java community, the gunman would probably written as a set of nested constructors:

benNadel = new Gunman( new Person( "Ben Nadel" ) );

... in which case, again, we are back to a situation where benNadel is sufficient in the given context.

Reply to this Comment

I think, in the general case, you are probably right about that not coming up very often, but jQuery has a pretty big gotcha when it comes to having raw dom nodes. Since just about everything except $.fn.extend() passes the raw dom node, we consistently find ourselves with a reference to a dom node and a need to wrap it.

$('div').each(function(){
var $this = $(this);
});

What is a better name for that?

$('div').each(function(){
var blogPost = $(this);
});

That works, but it can get a lot more convoluted with multiple sets, etc.

But I fundamentally agree that if we were able to describe this consistently and correctly, that I could support dropping the $.

Reply to this Comment

@Alex,

Using jQuery is so (relatively) new, that I don't think anyone is going to have the best approach to something like this (myself very much included in that). And, I am not sure how much we can borrow from any other scenarios (maybe XML-heavy languages)?

One thing that I have been playing around with using the type of node element as the variable name:

$( "form" ).each(function( index ){
var form = $( this );
});

This, however brings up a problem when I use A tags as "link" is a reserved word in Javascript (why must they have SO MANY reserved workds). As such, with links, I generally go with "trigger".

For things in which I can be more descriptive in terms of interface-intent, I will use names like "modal". But, I don't have many great examples of this.

Reply to this Comment

@Ben,

Also (just had another thought), another thing that I will do a lot is leverage the plural/singular contrast. Something like:

// All forms.
var forms = $( "form" );

forms.each(function(){
var form = $( this );
});

... here, the form never conflicts with formS.

Also, another thing to consider - even if we are dealing with singular references, due to the lexical-binding of Javascript, when creating event callbacks (Hollabacks), we might not even need to deal with "this" at all:

var a = $( "#myLink" );

a.click(function( event ){
a.text( "Ouch!" );
});

... here, even inside the callback, the original "a" variable is still available to the callback (although it will have to travel up one scope step to find it).

Reply to this Comment

Two years later is there a resolution? I like your example:

var tableNode = document.getElementById( "#tableId" );
var table = $( tableNode );

But doesn't "Node" just say what the data type is? Isn't that the same as prefixing a number with "num" or putting a suffix "List" on an array variable?

To me, the difference with jQuery, is it shares a kind of data with a native data type: DOM elements. So they both hold the same kind of data, but if you try to call native methods on a jQuery object or jQ methods on a native object you'll get errors. For that one reason I would differentiate the variables. But that's just me.

Reply to this Comment

I agree a lot with Aeron, the poster above. I'm new enough to jQuery that I feel like differentiation between the results of jQuery operations and javascript operations adds value, especially because jQuery's an addition onto the existing JS framework, but the languages' objects aren't fully interoperable.

I'm also dubious about your dismissal of HN and, by extension, the $-prefix notation, as being born of emotional satisfaction. These discussions and value judgments aren't about emotion, they're about communication. HN is an attempt to communicate extra information about variables cheaply. For myself, I don't use HN because usually the prefixed information is insufficiently useful to merit uglying up my variable names. But in the case of jQuery's $-prefix, there's very little uglification because $ is clearly not part of a variable name. Additionally, in a number of other environments, like DOS scripting and Perl, $-prefixing means roughly what it does here: this is a special object, you can do special things with it. Finally, even if my preference to use the $-prefix is born out of emotional attachment, I feel like it communicates to code readers everything about the variable more quickly and easily than leaving it bare.

Anyway, thanks for pointing out that the $-prefix isn't obligatory or demanded by the language, which was causing me some grief in the tutorials--again, jQuery's pretty new to me. :)

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.