When JavaScript hits a problem it can't handle, it creates an error (sometimes called an exception). Errors come in different types, and the type is your first big clue about what went wrong. Here are the four you'll meet most often:
| Error type | What it means | Common causes |
|---|---|---|
| SyntaxError | "I can't understand this code." | Missing brackets, quotes or commas. Typos in keywords. |
| ReferenceError | "I can't find anything with that name." | Typos in variable names. Using a variable before creating it. Wrong capitals. |
| TypeError | "You can't do that with this type of value." | Reading a property of undefined or null. Calling something that isn't a function. Reassigning a const. |
| RangeError | "That number is out of the allowed range." | Invalid array lengths. Recursion that never stops. |
Let's see each one in action.
SyntaxError
const scores = [10, 20, 30;
It stops with an error
Uncaught SyntaxError: Unexpected token ';'
JavaScript was expecting a ] to close the array, but found a ; instead.
ReferenceError
const userName = "Mia";
console.log(username);
It stops with an error
Uncaught ReferenceError: username is not defined
We created userName (capital N) but tried to use username (lowercase n). Remember: JavaScript is case-sensitive! This is probably the single most common error you'll ever see.
TypeError
const total = 50;
total.toUpperCase();
It stops with an error
Uncaught TypeError: total.toUpperCase is not a function
toUpperCase is a string method. Numbers don't have it. So total.toUpperCase is undefined, and you can't call undefined like a function.
RangeError
function forever() {
forever();
}
forever();
It stops with an error
Uncaught RangeError: Maximum call stack size exceeded
This function calls itself, which calls itself, which calls itself... forever, with no base case to stop it (remember recursion from Grade 6?). Eventually JavaScript runs out of room to keep track of all the calls and gives up. This error is so famous that a well-known programming help website is named after it: Stack Overflow.