04 - How to fix "Uncaught ReferenceError: x is not defined" in JavaScript
The important bits
- Uncaught ReferenceError: color is not defined means that you are trying to use a variable named color that doesn't exist (yet).
- This can often happen because your depenencies or code are out of order. One example: You are loading jQuery AFTER you try to use the $ variable that is added by jQuery.
Exercise - Now you try it
Transcript
So ReferenceError: color is not defined in JavaScript usually means that you are requesting a variable that doesn't exist. Either you haven't defined it or it wasn't defined at the time when you were requesting it. So let's look at this example here, we've got a variable called name and we assign it to Adam. And then down here, we're requesting a variable called color. And because that doesn't exist, we see here, ReferenceError: color is not defined. So the solution is to either fix this – Oh, now all of a sudden it exists – or we reconcile these names the other way, right? You do name and name. Now it doesn't matter if it's an object, you know, and you're calling it like color.getColor() things like this. It's always gonna fail. In this situation it's gonna fail because JavaScript is gonna throw an error here at this first part.
End Now here's an area where this commonly happens and people don't realize why. We'll switch to this one over here. So we're loading jQuery on this page and here in the script, we're using jQuery, we're using the $ variable, which is defined by jQuery. But if you see the order of these scripts, you can see that jQuery is loaded after we're trying to access the $ variable, which is why, again, we get the same thing. So if we run this, cannot find variable $ global. Okay. So this variable at this point is undefined. And it doesn't matter if we're doing it in a script on the page, or if we're doing it in an external file, like the script file, this is out of order. So in this case, we need to move the dependency earlier. We need to move jQuery earlier, because this code depends on the jQuery code being loaded in first. So let's try it again. And there we go. Now it works. Good luck.