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! While you're at it, check out some resources Treehouse students have shared here.
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 trialmebula
4,931 PointsHow 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
Jason Anello
Courses Plus Student 94,610 PointsHi 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
33,528 PointsI'm pretty sure jQuery uses the $
symbol and Javascript (vanilla) does not. $
is equal to jQuery()
.
james south
Front End Web Development Techdegree Graduate 33,271 Pointsthe 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.