ReferenceError: what this means and how to debug it
// let’s calculate Х to the power of Y and save it into ‘result’
result = math.pow(x,y);
If you run that code, you may see:
❌ ReferenceError: math is not defined
This is nothing to worry about. Here is what’s happening:
- The built-in library for mathematical functions is called ‘Math’ with a capital M. And our source code has a lowercase m.
- All we need to do is say ‘Math’ instead of ‘math,’ and we are good:
✅ result = Math.pow(x,y);
Why you get reference errors
There is a typo in a variable or function name. See which line the error is occurring in, go to that line in your code, and check for typos. You might have missed a semicolon or put in an extra space.
You’re trying to call a function or a variable that’s outside your current scope. For example, you may be trying to reach a variable that lives inside one function, while you are in another function. Two functions will most likely not see each other’s variables, so you can’t get them to talk directly.
The function or method you’re calling hasn’t been declared correctly. For example, say you’re using a plugin library that has a function like showGallery(); If you get a reference error for showGallery(), it’s likely that one of these things is true:
● showGallery’s main code didn’t load properly. Check where you’re pointing your <script> command.
● showGallery’s main code is corrupt or conflicts with something else on your page.
Either way, start by investigating the original code, including when and where it is loading. Also, feel free to check out my previous article about jQuery and ‘$ is not defined’ — the problem is similar.
Good luck, and happy debugging!
If you found this tutorial helpful, consider learning more on Practicum. We offer online education and mentorship to help you build your career in tech.