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 trial

JavaScript AJAX Basics (retiring) AJAX and APIs Stage 4 Challenge Answer

Jaime Jayne
Jaime Jayne
882 Points

difference between var $variableName and var variableName

My solution for the challenge worked, but wondering what the difference is. var searchTerm = $("#search").val(); var flickrOptions = { tags: searchTerm, format: "json"

Whereas the solution provided used: var $searchTerm = $("#search"); var animal = $searchTerm.val(); var flickrOptions = { tags: animal, format: "json"


My main curiosity is the difference between defining a variable and a Jquery variable. Thanks

2 Answers

Jaime Jayne
Jaime Jayne
882 Points

Thanks Gareth Borcherds! In addition to your explanation (that there is little difference btwn $var and var) I also now understand that the $ is used more like a visual guide to indicate the type of data stored in the variable. In my example: var searchTerm = $("#search").val(); stored the returned value (in this instance text) into the variable, whereas the suggested solution var $searchTerm =$("#search") stored the Jquery object into the variable - which you could later use to manipulate with other jquery methods.

Dave McFarland
Dave McFarland
Treehouse Teacher

That's right. The $ is just used to indicate that the value stored in the variable is a jQuery object.

Gareth Borcherds
Gareth Borcherds
9,372 Points

There is no difference when you have var in front of both. They are just a different variable name. A lot of programmers like to put the $ sign in there because it helps differentiate variables in the code and keeps things cleaner. But there is no real difference, it's like a different spelling of the name.

Now if you removed the var, then you would be changing the scope of the variable, but that's a different topic.