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

Gareth Borcherds
Gareth Borcherds
9,371 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.

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.