Why error “$ is not defined” occurred in jQuery ?

One of the most common errors faced by jQuery developers is the ‘$ is not defined’ error. At first, it may seem like a small error, but considering the fact that more than 70 percent of the website uses jQuery in some form or other, this may turn out to create a huge mess.

Reason behind this error: 
This error basically arises, when the developer is using a variable, before declaring it in the script. 

Example:  

filter_none

edit
close

play_arrow

link
brightness_4
code

// ReferenceError: num is not defined
num;
 
declaration
var num;
 
// No more errors
data;
chevron_right

Output: 
 



In the above example, we see that ‘num’ has been called before it was declared. This is why ReferenceError: num is not defined was thrown in the first line. In the third line, ‘num’ is called again. However, no error will be thrown this time, as the variable has already been defined in the second line of the script.

This is a very common error. The best way to avoid this is to hoist all the variables and functions before calling them. Have a look at another example. 

Example:  

filter_none

edit
close

play_arrow

link
brightness_4
code

//reference error
process();
 
process = function(){
var a = 2;
console.log(a);
}
 
// no error
process();
chevron_right

Output: 
 

Most common reasons for this error: 

Correct Order: 

filter_none

edit
close

play_arrow

link
brightness_4
code

<script src="/lib/jquery.min.js"></script>
<script src="/lib/jquery.plugin.js"></script>
chevron_right

Example: 

filter_none

edit
close

play_arrow

link
brightness_4
code

//an external CDN link
<script src=
</script>
 
//fall back to local jQuery
<script>
window.jQuery || document.write('
<script src="http://www.mywebsite.com/jquery.min.js"><\/script>'))
</script>
chevron_right

 





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : Akanksha_Rai, Vijay Sirra

Article Tags :