Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

How to determine if I should use $ before a variable name?

This may have been explained somewhere, but how do you determine if you should set $ before a variable name in JS? I have an example below.

var color = $(".selected").css("background-color");
var $canvas = $("canvas");
var context = $canvas[0].getContext("2d");

3 Answers

Hi Mei,

If you're following that convention, then you would put a $ in front of any variable name that is storing a jQuery object.

For the first line, that code is retrieving the value of the background color for the select element. This is going to come back as a simple string and not a jQuery object. So the color variable would not have a $ in front because it's storing a string.

The second example is selecting the canvas element and wrapping it in a jQuery object. The canvas variable would get the $ in front since it is storing a jQuery object.

The 3rd example is accessing the canvas element itself with $canvas[0] and then calling the getContext() method on that. This returns a drawing context and not a jQuery object so the context variable doesn't get the $ prefix.

Kyle Johnson
Kyle Johnson
33,527 Points

I'm pretty sure jQuery uses the $ symbol and Javascript (vanilla) does not. $ is equal to jQuery().

james south
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
james south
Front End Web Development Techdegree Graduate 33,258 Points

the dollar sign is the jquery alias. if you are just using plain JS you probably wouldn't be putting it in front of your variables. in jquery it denotes a jquery object. it is a shorthand notation for jquery.