Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript jQuery Basics (2014) Creating a Simple Drawing Application Perform: Part 1

When to us $ in the beginning of a variable and when not?

What is the reason why there is no $ before the color variable in this exercise?

var color = $(".selected").css("background-color");

$(".controls li").click(function(){



  color = $(this).css("background-color");

4 Answers

Hi Sauli,

It's a good practice to precede a javascript variable name with a $ if that variable is storing a jQuery object. It's not something you have to do but can help with reading the code. Of course, this gets misused by some people and so you can't assume a variable preceded with a $ is in fact storing a jQuery object.

Since the following $(".selected").css("background-color") returns a string with the color you shouldn't use $color.

Let's say you wanted to do multiple things with the .selected element. You can first store that jQuery object in a variable.

var $selected = $(".selected"); // Here I've used the $ in front of the variable name to indicate that it's storing a jQuery object
var color = $selected.css("background-color"); // Here I can use that variable to get the background color. The color variable doesn't get the $ for reasons stated above
// Do some more stuff with $selected

It's not required to put the $ in front of selected but it can help you and others reading your code.

Marked as best answer

Thomas Horner
Thomas Horner
11,185 Points

In Javascript you don't add $ to make a variable. To create the variable in Javascript you use "var", like they show in line 1. In the last line when color is used, you don't need to use "var" again since the variable is already called, you are simply updating or reassigning the variable to $(this).css("background-color");

The $ sign is used in jQuery to start their commands. It's simply shorthand for jQuery so you don't have to retype "jQuery" every time. Like this:

var color = jQuery(".selected").css("background-color");

jQuery(".controls li").click(function(){



color = jQuery(this).css("background-color"); })

Ok. Is this also the reason why the variable color does not have a $ before it (e.g. $color)?

Ok, now I understand. Thanks.