What do the error messages mean in my console? (JavaScript)
Did you know that the error messages you see in the console actually contain clues to solving the error? Yes! It’s true!
Let’s take a look at one common error and dissect it to figure out how to solve it. If you're working in CodeSandBox you are likely to come across an error that looks like this:
The console tells you that you're dealing with a Syntax Error and that it's in the /js/script.js file.
If you expand that error, you will see a lot more information. In addition to seeing the file that triggered the error, we see a more precise indication of where in the code the error occurred. Below it, you'll see what is called a "stack trace", which lists all files that were involved in generating the JavaScript up until your file was parsed. In the overwhelming majority of cases, you don't need to pay attention to the stack trace, but it's good to know that it exists if ever you need to dig deeper.
In the console of your web browser, you'll have access to the same information provided in the console on CodeSandbox.
In addition to the console, CodeSandbox also provides us with a "Problems" tab, which often helps us get to the root of an error more quickly:
Nice!
JavaScript errors fit in one of many categories. The most common are:
Reference Errors
Reference errors typically have to do with variables that you are trying to use that don't exist yet (or at all). Typos in variable names are very often the cause of this error, but again, the console will steer you in the right direction.
Syntax Errors
The most common type of error happens when JS is unable to understand part of our code. Perhaps we forgot the second pair of quotes or added an errant character somewhere by mistake. The console will show you where the problem is.
Type Errors
Type errors happen when your JS code is trying to manipulate a variable of a certain type in a way that isn't possible. For example, if you try to make a variable of type number uppercase, or if you try to use a "toFixed" method on a variable of type string. The feedback in the console for this type of error is often "variableOfWrongType.function is not a function" - meaning, that the function in question isn't available for that particular type of variable.
There are other types of errors, but the three listed above are the ones you will run into most frequently.
Obligatory JavaScript Disclaimer: In some rare cases, the errors we make are too hard for the JavaScript interpreter to figure out. It may tell you that there is an error on a line that has no code on it, or that doesn’t even exist. If that happens, you just have to look at all of your code very carefully. One helpful thing to do is comment out all of your code, then comment it back in line by line, or block by block, until the error comes back. When the error comes back, you’ll know the error must be in that line or block.