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

A simple question.

Hello and thank you for reading and answering this question, as I was reading the answer of this coding challenge I saw that Dave McFarland wrote this code:

var $searchField = $('#search');

But I wrote it like this:

var searchField = $('#search');

What is the difference between these two? Why Dave choose the first method?

Thank you, very much appreciated :smiley:

2 Answers

Ellis Briggs
Ellis Briggs
11,108 Points

I believe the first one just helps show that it is a Jquery object instead of a normal JS one.

But they should work the same

Thank you very much, Ellis.

Alexander Gyger
Alexander Gyger
14,237 Points

With your notation, be aware that your variable also without the "$" is still a jQuery object. Usually if you make a jQuery object variable it's good practice to use a "$" at the beginning of it to make it readable.

These are both jQuery objects

var $searchField = $('#search');

If you write it like this:

var searchField = $('#search');

they are both still jQuery objects. But without the "$", the variable could be misread in a long code as a regular JavaScript variable.

If you want to use it as a regular variable (just a string) like i did in my solution, you could have added the ".val()" already here

var searchTag = $('#search').val();

This is now just a regular non-jQuery string variable.

Thanks for the reply Alexander